I am writing a class to consume 'ALL' input from barcode scanner. I am using the code from http://nicholas.piasecki.name/blog/2009/02/distinguishing-barcode-scanners-from-the-keyboard-in-winforms/
I've added following lines in PreFilterMessage() for testing.
if (m.Msg != Win32.WM_INPUT)
{
// Allow any non WM_INPUT message to pass through
return false;
}
return true;
The problem is with some barcode that has "═" (Alt + Numpad: 205) in it. and it gets typed in the textbox. How can I prevent the Alt + Numpad keys from dispatching?
I am able to handle this issue by catching the keys at form level, by setting the form
keypreview=true,
and in form_keypress event setting
//if(Alt pressed && numpad keys)
e.Handled = true;
But ideally this should be handled by the class. Any ideas??
How about checking modifier keys to block Alt+Numpad keys?
E.g.
if (ModifierKeys == Keys.Alt)
return true;
Related
I have a problem using Sendkeys.Send in my C# application and I really cannot understand why. When using it then it does not send what I expect to the active application. I am using it together with the global hotkey manager, https://github.com/thomaslevesque/NHotkey
I have created this simple PoC that, for my part at least, will be able to reproduce my problem. Just launch Wordpad and press the hotkey, ALT + O:
using System.Windows.Forms;
using System.Diagnostics;
using NHotkey.WindowsForms;
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Convert string to keys
string hotkey = "Alt + O";
KeysConverter cvt;
Keys key;
cvt = new KeysConverter();
key = (Keys)cvt.ConvertFrom(hotkey);
// Setup the hotkey
HotkeyManager.Current.AddOrReplace("MyID", key, HotkeyAction);
// Copy some text to the clipboard that I want to paste to the active application
Clipboard.SetText("My String");
}
private void HotkeyAction(object sender, NHotkey.HotkeyEventArgs e)
{
Debug.WriteLine("Pressed the hotkey");
SendKeys.Send("^v");
// SendKeys.Send("Test string");
e.Handled = true;
}
}
}
When I do this in Wordpad, then instead of pasting the clipboard (^v equals CTRL + V) then it tries to "Paste Special":
Even if I do the most simple thing and then just put some text in SendKeys.Send, then it seems to be messing with the menus in Wordpad? SendKeys.SendWait is not any different.
I have been trying to figure this out for quite some time now but I simply do not understand why it does that. Basically, I need to paste the clipboard on a hotkey though it doesn't need to be with this exact method so if anyone knows another way of doing it then I would appreciate some hints.
MY IMPLEMENTED SOLUTION
Based on the accepted answer then I did change my implementation slightly as I could not get it working with just a timer. I may have missed something(?) but this is working.
In basic then I change focus to my application as soon as the hotkey is detected, to avoid conflict with modifier keys (ALT etc) in the active application. I then create an invisible form and when I detect a KeyUp event, then I check for modifier keys and if none is pressed down then I enable a timer and immediately switch focus back to the originating application. After 50ms the clipboard will be pasted to the active application.
Something like this:
// Somewhere else in code but nice to know
// IntPtr activeApp = GetForegroundWindow(); // get HWnd for active application
// SetForegroundWindow(this.Handle); // switch to my application
private System.Timers.Timer timerPasteOnHotkey = new System.Timers.Timer();
// Main
public PasteOnHotkey()
{
InitializeComponent();
// Define the timer
timerPasteOnHotkey.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timerPasteOnHotkey.Interval = 50;
timerPasteOnHotkey.Enabled = false;
// Make the form invisble
this.Size = new System.Drawing.Size(0, 0);
this.Opacity = 0.0;
}
private void PasteOnHotkey_KeyUp(object sender, KeyEventArgs e)
{
// Check if modifier keys are pressed
bool isShift = e.Shift;
bool isAlt = e.Alt;
bool isControl = e.Control;
// Proceed if no modifier keys are pressed down
if (!isShift && !isAlt && !isControl)
{
Hide();
// Start the timer and change focus to the active application
timerPasteOnHotkey.Enabled = true;
SetForegroundWindow(activeApp);
}
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
timerPasteOnHotkey.Enabled = false;
SendKeys.SendWait("^v"); // send "CTRL + v" (paste from clipboard)
}
When you use SendKeys.Send in a response to a key press then the keys you send may be combined with the physical keys you’re holding at that moment. In this case you’re holding Alt, so Wordpad assumes you pressed Alt-Ctrl-V instead of just Ctrl-V. Also Alt opens menu, so sending other keys may relate to hotkeys there.
Adding a delay will remove this issue, and usually when sending key presses it would be done as not relating to other key presses so it won’t be a problem.
i want to know whether user is typing using the shift key still pressed or not and log that like (Shift + T + R + Y).
i am not able to do so.
Add this code in Your Keydown event
if (e.Modifiers == Keys.Shift)
{
// This code will only be triggered when shift is pressed along with any other key.
}
I'm making a custom Terminal in a C# winform. When the user presses a key in the TextBox that I'm using I have to make sure that it's a valid key. I need to prevent them from being able to delete stuff and do whatever they want. I managed to handle the backspace and delete and others via the KeyPress and KeyDown events. I had a problem with the user pressing shift + delete. It deletes stuff just like backspace. I don't know what the integer equivalent of it is. I made a C++ program to detect it, it was simple:
char c = _getch();
cout << (int)c << endl;
I got a -32. It didn't work in C#.
After so many tries to encircle its value, I found that it was 0.
It worked, at least for yesterday, but now it doesn't. I'm also able to delete stuff with the shift+delete.
Here's my key validation method:
private bool IsInvalidKey(char key)
{
bool condition1 = !IsAsciiKey(key) && !IsNavigatingKey(key); // by navigation I mean: left, right, end and home keys.
bool condition2 = (GetCaretPosition() == CaretPosition.OutsideCommandLine && !IsNavigatingKey(key));
bool condition3 = ((key == (char)Keys.Back) && GetCaretPosition() == CaretPosition.BeginningOfCommandLine);
return (condition1 || condition2 || condition3);
}
private bool IsAsciiKey(char key)
{
return ((int)key > 0 && (int)key <= 127); // char(0) should be shift+delete
}
How can I detect this key and where (in which event, KeyPress or KeyDown?)
I'm using a normal TextBox control, not a RichTextBox.
You could try something like this in the KeyDown event.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Shift && e.KeyCode == Keys.Delete) e.Handled = true;
}
Rather than trying to look at each individual key through the use of the KeyDown event, what you really need to do is do all of your validation in the TextChanged event, and you need to validate the entire entry (not just the last character) every time anything changes. This is the only way to support everything that the user could possibly do. As an example, the user could use the mouse to cut or paste text in the textbox, and that doesn't trigger any key press events at all.
If you want, you can handle the key press event as well so that you can prevent invalid characters/key from changing the text in the first place (and causing a full validation) but that's basically like performing client side validation of a field on a webpage; it's nice to do, but since you can get around it you can't only use it.
I'm currently working on a simple game that is drawn on a form by overriding the OnPaint method. The game requires Keyboard input and was working perfectly until I decided to enhance the GUI and add a few Buttons to the form.
The moment I added these Buttons, the form stopped receiving any Keyboard input, no matter how hard I tried the focus was always on the buttons. This behavior can be replicated by placing any Focus-able Control on the form. (ie. TextBox)
I don't need ANY Kayboard interaction with these buttons, I want the user to interact with them with the mouse only.
I've tried the following techniques to try and get around this problem - none of these worked:
1) Normal KeyDown and KeyUp events of the form. (This is the way
I was capturing Keyboard input before placing the buttons.)
2) Overriding the Form's OnKeyDown and OnKeyUp events.
3) Overriding ProcessCmdKey - Works, but cannot differentiate
between KeyUp and KeyDown events, so it is inadequate for me.
I also tried create a MessageFilter for the application, but I couldn't force it to capture only the Keyboard keys that I needed.
I've been looking into this for many hours already and can't find a suitable solution.
Help would be greatly appreciated.
Here is a sample form with a IMessageFilter for the up and down arrow keys, hope this helps:
public partial class MainForm : Form
{
private class MessageFilter : IMessageFilter
{
public MainForm Main { get; set; }
public bool PreFilterMessage(ref Message msg)
{
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
if (msg.Msg == WM_KEYDOWN)
{
var keyData = (Keys)msg.WParam;
if (keyData == Keys.Down || keyData == Keys.Up)
{
return true; // Process keys before return
}
}
else if (msg.Msg == WM_KEYUP)
{
var keyData = (Keys)msg.WParam;
if (keyData == Keys.Down || keyData == Keys.Up)
{
return true; // Process keys before return
}
}
return false;
}
}
public MainForm()
{
this.InitializeComponent();
Application.AddMessageFilter(new MessageFilter { Main = this });
}
}
For a list of possible Windows messages check:
List Of Windows Messages
Set the KeyPreview property of the form to True, and then set event.Handled = True when you handle KeyDown/KeyUp. This will ensure that the form gets a chance to handle events before its children. Because you set the handled property to true, the childen won't see the keyboard events.
More info here: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx
I need to capture keystokes from a wedge device and prevent any controls or the form from receiving them. I also need to be able to know the value (char). I have tried overriding the ProcessCmdKey(Keys) and ProcessDialogChar(char) events. In the ProcessCmd event I can suppress the keystroke if it's one I want, but I the character isn't a parameter of the event. In the ProcessDialogChar event the character is there, but I cannot prevent the form or control with the focus from receiving the key. Suggestions?
You'll want to add this during Form load:
Application.AddMessageFilter(this);
Add this constant:
private const int WM_KEYDOWN = 0x100;
And this method:
public bool PreFilterMessage(ref Message m)
{
Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode;
bool retVal = false;
if (m.Msg == WM_KEYDOWN)
{
// Handle the keypress
retVal = true;
}
return retVal;
}
By returning true, your form and control(s) will never see the key press.
It was not how I wanted to do it, but because I needed to fix this and move on I put a hidden textbox on the form and as soon as I see the character that signals the possible start of the string of data I want to capture I set focus to that text box and respond to the TextChanged event. If I haven't seen the ending character before I timer expires I clear the textbox and start again. Kludge, but it works and got me to the next task.