Arrow key events not arriving - c#

Basically, I have a form with a custom control on it (and nothing else). The custom control is completely empty, and the form has KeyPreview set to true.
With this setup, I am not receiving any KeyDown events for any arrow keys or Tab. Every other key that I have on my keyboard works. I have KeyDown event handlers hooked up to everything that has such events, so I'm sure I'm not missing anything.
Also of note is that if I remove the (completely empty) custom control, I DO get the arrow key events.
What on earth is going on here?
EDIT:
I added this to both the form and the control, but I'm STILL not getting arrow keys:
protected override void WndProc(ref Message m) {
switch (m.Msg) {
case 0x100: //WM_KEYDOWN
//this is the control's version. In the form, it's this.Text
ParentForm.Text = ((Keys)m.WParam).ToString();
break;
}
base.WndProc(ref m);
}
I also checked with Spy++, and determined that the form itself is not getting any WM_KEYDOWN messages, they're all going to the control. However, that said, the control IS getting the arrow key WM_KEYDOWN messages. Sigh.
Edit 2: I've also updated the ZIP file with this version. Please look at it, if you want to help...
Edit 3:
I've figured this out, sort of. The form is eating the arrow keys, probably in an attempt to maintain focus amongst its children. This is proven by the fact that I DO get the events if the form is empty.
Anyway, if I add this code to the form, I start getting the events again:
public override bool PreProcessMessage(ref Message msg) {
switch (msg.Msg) {
case 0x100: //WM_KEYDOWN
return false;
}
return base.PreProcessMessage(ref msg);
}
When I override this, the form doesn't get a chance to do its dirty work, and so I get my KeyDown events as I expect. I assume that a side effect of this is that I can no longer use my keyboard to navigate the form (not a big deal in this case, as it's a game, and the entire purpose of this exercise is to implement keyboard navigation!)
The question still remains about how to disable this "properly", if there is a way...

I've done some extensive testing, and I've figured everything out. I wrote a blog post detailing the solution.
In short, you want to override the ProcessDialogKey method in the form:
protected override bool ProcessDialogKey(Keys keyData) {
return false;
}
This will cause the arrow keys (and tab) to be delivered as normal KeyDown events. HOWEVER! This will also cause the normal dialogue key functionality (using Tab to navigate controls, etc) to fail. If you want to retain that, but still get the KeyDown event, use this instead:
protected override bool ProcessDialogKey(Keys keyData) {
OnKeyDown(new KeyEventArgs(keyData));
return base.ProcessDialogKey(keyData);
}
This will deliver a KeyDown message, while still doing normal dialogue navigation.

If focus is your issue, and you can't get your user control to take a focus and keep it, a simple work-around solution would be to echo the event to your user control on the key event you are concerned about. Subscribe your forms keydown or keypress events and then have that event raise an event to your user control.
So essentially, Form1_KeyPress would Call UserControl1_KeyPress with the sender and event args from Form1_KeyPress e.g.
protected void Form1_KeyPress(object sender, KeyEventArgs e)
{
UserControl1_KeyPress(sender, e);
}
Otherwise, you may have to take the long route and override your WndProc events to get the functionality you desire.

Related

Can't escape from ToolStripTextBox in a particular case

It is hard to describe the issue. Let me illustrate it with a very simple example.
Start from a new solution of winform(.net framework 4.8).
Add a menustrip with a textbox, then a datagridview.
And let's handle KeyDown event of datagridview.
if (e.KeyCode == Keys.F3)
toolStripTextBox1.Focus();
Ok, now we start the program.
Click the datagridview to focus on it.
Click the textbox to change focus.
Press Esc on your keyboard.
You can see that the datagridview gets the focus as expected.
But if you make a little change in step two, the result will be confusing.​ Press F3 instead of clicking the textbox.​ When you press Esc this time, the focus is just lost.​ I tried to print the name and the handle of focused control. It turned out to be the textbox itself.​ Can somebody explain it?
Now I'm quite sure it is some kind of bug. After Jimi's mention of hwndThatLostFocus, I had traced this variable for several hours. Although I failed to locate the exact position where hwndThatLostFocus was changed, something unreasonable was found: when Focus() was called in different cases, the result lost consistency.
Under most circumstances, if Focus() of ToolStripTextBox is called, hwndThatLostFocus of ToolStripTextBox will be set to 0, just like the example in my question. But if you click the datagridview and click the ToolStripTextBox and then click the datagridview agian, this time you call Focus(), hwndThatLostFocus will remain a pointer to the datagridview. In addition, this could be reproduced in .net 6.
Later I will report this to Microsoft. For now, there are three ways to avoid this.
Simulate a mouse click by SetCursorPos and mouse_event in user32.dll.
Use reflection like Jimi's advice.
Override ProcessCmdKey in Form, and take care of Keys.Escape yourself:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape && msg.HWnd == toolStripTextBox1.TextBox.Handle)
{
dataGridView1.Focus();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
As I avoid using unnecessary reflect, and Dllimport is also some kind of ugly to me, I prefer the third one.

Passthrough all mouse events but not stylus events

I am making an application for personal use where the stylus can be used to draw on the current screen but the normal use (with mouse) won't be interrupted.
Currently, I am trying to use WS_EX_TRANSPARENT to set the window to allow mouse events through, but it seems like that stylus events also get passed through without being captured.
Is there any other method I can use to pass through mouse/keyboard events while still allowing stylus events? Here is what my program looks like so far:
Disable the RealTimeStylus for WPF Applications on MSDN states:
[...] (WPF) has built in support for processing Windows 7 touch input [...] Windows 7 also provides multi-touch input as Win32 WM_TOUCH window messages. These two APIs are mutually exclusive on the same HWND.
This seems to imply that, for a given window, you can receive stylus events or touch events but not both. As you do want to handle the stylus events this means you don't need to bother filtering the touch events. That just leaves the mouse and keyboard.
At first I thought you might be able to use a custom window procedure (WndProc) and filter-out the mouse and keyboard messages. However, the WndProc (when used in WPF) is really just a notification mechanism and you can't block the received messages.
I found a Windows API called BlockInput that supposedly "Blocks keyboard and mouse input events from reaching applications". However from the docs this appears to be system-wide not app-specific so may not be any use to you.
The only other way I can think of is to use a low-level keyboard or mouse hook. This requires some P/Invoke but it's not too difficult. These hooks allow you to register callback functions that get called when keyboard and mouse events are raised. The advantage is that you can prevent those events from propagating and effectively "swallow" them, which sounds like what you need.
I don't really like posting an answer that basically says "do a search for ..." but the amount of code involved is non-trivial and has been posted in numerous places both on Stack Overflow and elsewhere, so: try doing a search for low level keyboard hook c# wpf and you should find some code that might help!
One thing you may have trouble with even if you go down this route is focus. As soon as your "invisible" topmost window gets a stylus message that it responds to, I'm presuming focus will switch to your WPF application, thus "stealing" focus from whatever application was being used prior. You might be able to use P/Invoke again to set the window style flags of your main window to prevent this (as per the accepted answer to this SO question).
ORIGINAL ANSWER
You can override the appropriate keyboard, mouse and touch Preview... event handler methods of the Window and mark them as handled. This has the effect of stopping child controls from receiving those events.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
e.Handled = true;
base.OnPreviewKeyDown(e);
}
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
e.Handled = true;
base.OnPreviewMouseDown(e);
}
protected override void OnPreviewMouseMove(MouseEventArgs e)
{
e.Handled = true;
base.OnPreviewMouseMove(e);
}
protected override void OnPreviewMouseWheel(MouseWheelEventArgs e)
{
e.Handled = true;
base.OnPreviewMouseWheel(e);
}
protected override void OnPreviewTouchDown(TouchEventArgs e)
{
e.Handled = true;
base.OnPreviewTouchDown(e);
}
protected override void OnPreviewTouchMove(TouchEventArgs e)
{
e.Handled = true;
base.OnPreviewTouchMove(e);
}
}
I've done the basic keyboard, mouse and touch events here. In a simple app test it seemed to do the trick and I assume it would still let stylus events through (I don't have a stylus I can test with).
You may have to experiment with which events need to be handled like this. I only did KeyDown for example, not KeyUp as I presume the latter is irrelevant without the former. I may also have implemented some that didn't need to be handled, and I'm not sure the calls to the base methods are needed either. As I say, experiment until you get something that works for you.

Forms not responding to KeyDown events

I've been working for a while on my Windows Forms project, and I decided to experiment with keyboard shortcuts. After a bit of reading, I figured I had to just write an event handler and bind it to the form's KeyDown event:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.Alt && e.KeyCode == Keys.O)
{
MessageBox.Show("Ctrl+Alt+O: magic!");
}
}
I did that the good ol' way of opening the Properties panel of the Visual Studio designer, then double-clicking on the KeyDown event of my form to generate the Form1_KeyDown event handler. But on testing my application, the form doesn't respond at all to the Ctrl+Alt+O keyboard shortcut. The Visual Studio designer did generate the code to bind the event handler to the form though:
private void InitializeComponent()
{
// ...
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
// ...
}
So I tried adding a Console.WriteLine() call to the handler to check that it was being called at all, but no luck on that either.
Also, I tried to set a breakpoint on the event binding call (shown just above) and found that the program reaches that breakpoint just fine. But any breakpoints I set within the method definition itself are never reached.
To make sure I was doing the first few steps correctly, I tried repeating them with:
A new form in the same solution.
Same issue: the form doesn't respond when I press my Ctrl+Alt+O keyboard shortcut and the debugger isn't even stepping into the event handler. Tried this again and it works.
A brand new WinForms solution.
It works perfectly: the message dialog appears (the Console.WriteLine() call also works).
So I'm quite lost here. What's preventing all the forms in this one project from receiving KeyDown events?
Does your form have KeyPreview property set to true?
Form.KeyPreview Property
Gets or sets a value indicating whether the form will receive key
events before the event is passed to the control that has focus.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx
The most common piece of advice for this problem on StackOverflow and the MSDN1, 2 (including the accepted answer here) is quick and easy:
KeyDown events are triggered on a Form as long as its KeyPreview property is set to true
That's adequate for most purposes, but it's risky for two reasons:
KeyDown handlers do not see all keys. Specifically, "you can't see the kind of keystrokes that are used for navigation. Like the cursor keys and Tab, Escape and Enter for a dialog."
There are a few different ways to intercept key events, and they all happen in sequence. KeyDown is handled last. Hence, KeyPreview isn't much of a preview, and the event could be silenced at a few stops on the way.
(Credit to #HansPassant for those points.)
Instead, override ProcessCmdKey in your Form:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.Up)
{
// Handle key at form level.
// Do not send event to focused control by returning true.
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
That way, all keys are visible to the method, and the method is first in line to see the event.
Note that you still have control over whether or not focused controls see the KeyDown event. Just return true to block the subsequent KeyDown event, rather than setting KeyPressEventArgs.Handled to true as you would in a KeyDown event handler. Here is an article with more details.
Try setting the KeyPreview property on your form to true. This worked for me for registering key presses.

c#/winforms: application wide keyboard shortcuts with exception on editable controls

in my c#/winforms application i would like to do something like application wide keyboardshortcuts, which should be triggered anywhere, except if the focus is in a control where the user can edit text, like a textbox.
currently i am overwriting this function to do this.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData);
how can i add an exception to this, that it is not triggered when the user is in an editable control?
thanks!
I see 2 solutions here.
1) in each editable control, handle all keyboard events and in the eventArgs object, set the Handled property to true;
e.Handled = true;
2) before executing the wide keyboard shortcut, look for the control which has the focus, and if it's a TextBox, ignore it. There's probably a method in each Form to tell what Control has the focus.
The second option is cleaner. I don't give code because I don't have Visual Studio open right now, but if you need more specific code you can ask.
PS: here, I did some googling for you: How to Get FOcused Control?

Can I handle a key up event even when grid view isn't focused?

I have a Data Grid View inside a control that is displayed in a certain area in an application.
I'd like this activity grid to refresh when F5 is pressed.
It's easy enough to do this when the Activity Grid View is the currently focused element on the screen by handling the Key Up event, but this obviously doesn't work when another element (e.g. the menu bar) was the last thing that was clicked on.
Is there a way to track key presses in this case as well? I don't have access to the code outside my data grid view/control.
The answer to this may be a clear no, but I wanted to make sure I wasn't missing something obvious in making this work.
No.
If you don't have access to the other controls that may have focus at the time, there's no way to pass the key up message from them to your control.
You can do some global keyboard event handling on the Form the controls are on.
If you add this to your form you can get the global key events before they are send to the control.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.F5:
// Send Refesh Event To Grid
return true; // Mark Key As Handled
// Add Any Extra Command Keys Here
}
return base.ProcessCmdKey(ref msg, keyData); // Resend To Base Function
}
Have you tried to capture the event on the Form itself and then call the event handler for the data grid? You'll have to set KeyPreview to true for the form to get notified of keyboard events.
The best way to handle this, is to get the main application form to handle all keypresses.
In order to do this, set the main Form property "KeyPreview" to True.
Then, handle all your KeyUp events on the main form.
More information on KeyPreview here: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx

Categories

Resources