Forms not responding to KeyDown events - c#

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.

Related

Possible to ask for a keypressed signal at a centralized location in a paneled form?

I've got a winform application. In the application I have a Panel with multiple Buttons.
Now when the Buttons don't have the Focus I can capture the keypressed Events in the form itself. But when the Buttons have the Focus the form (even if the Buttons don't catch the Event explecitely) only they get the keypressed Event and not the form.
Now my question is: Is there any way to centralize the keypressed behaviour (without creating a keypressed Event for each and every button and call a central method with that Event)?
In essence only 1 method needs to be defined with the appropriate Parameters:
Example:
private void Event_Key_Press_Check(object sender, KeyPressEventArgs e)
This method then only Needs to be put in as the Name of the method used in the Event (form designer), or added as the Event.
That way only 1 method is used.
Thus there is no shorter way and the Event Needs to be defined for every single button (instead of 1 central Event that is always triggered).
Set form property KeyPreview to true and set KeyPress handler. Then form will handle this event before buttons.
See KeyPreview MSDN documentation.
I've had the same issue, and it was pretty easy to resolve :)
Check here : KeyPress at form level with controls
Just set the KeyPreview property (of your form) to True. This way your form will handle KeyPress event before any other control, even if one of them has the focus

How to handle spacebar keydown

It seems that the keydown event does not handle spacebar presses unless the control has focus. How do I, though?
I am using c# and I am making a windows store app, if it matters.
I'm not sure of what code you have within your project already but I'd recommend some JQuery along the lines of:
$(window).keypress(function(e) {
if (e.keyCode == 0) {
console.log('Space pressed, here is my event');
}
});
As the event is bound to a Window event, it will find it regardless of whether an input field is focused or not.
I figured it out.
Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
captures all key events.

How do I read keyboard input on a Winform?

I've tried using the KeyUp and KeyDown events to read keyboard input but as soon as I place other controls on the Winform, the keys are not read. How do I make sure that the keys are read?
You could set KeyPreview = true on your form to catch keyboard events.
EDITED to let you understand:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
e.SuppressKeyPress = true;
}
Stupid sample that receives keyboard events and drop if A was pressed.
If focus is in a textbox, you'll see that text is written, but not A!!
EDITED AGAIN: I took this code from a VB.NET example.
In your usercontrol, use the text box's "Keypress" event to raise a "usercontrol event".
This code would be in your custom usercontrol:
'Declare the event
Event KeyPress(KeyAscii As Integer)
Private Sub Text1_KeyPress(KeyAscii As Integer)
RaiseEvent KeyPress(KeyAscii)
End Sub
See: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx
set KeyPreview = true and your KeyUp and KeyDown will recognize all keyboard input.
As marco says set KeyPreview to true on your form to catch the key events in the entire form rather than just a control.
Use the KeyPress event ... KeyUp/Down are more for the framework than your code. KeyDown is good if you want to disable a key ... numeric only fields etc. In general KeyPress is the one you're after.
If you want to prevent the keystrokes from propogating to other controls set KeyPressEventArgs.Handled = true.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx
Have you wired up the event handler?
MyForm.KeyDown += MyHandler;
You can also do this in the properties pane ... click the event icon ...
If you are looking for your Form itself to read the keyboard input, you already have your answer from other correspondents. I am adding this contribution for the possibility that you might want to add key handling to other controls or user controls on your form. My article Exploring Secrets of .NET Keystroke Handling published on DevX.com (alas, it does require a registration but it is free) gives you a comprehensive discussion on how and why all the various keyhandling hooks and events come into play. Furthermore, the article includes a "Keystroke Sandbox" utility for free download that actually lets you see which controls are receiving which key handling events.
Here is one illustration from the article to whet your appetite:

OnLostFocus is called after dispose is called in a dataGridView

I Have a control inheriting the dataGridView control.
I have the onLostFocus method overrided. Lately I encountereda weird behavior. if trying to close the form while a cell is in teh middle of being edited. the dispose method will be called and then teh onLostFocus is called that results in a nullReferenceException
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
base.DefaultCellStyle = myStyle1;
}
}
my question is how come the lostFocus is called after the userControl starts being disposed?
and what is the correct way to handle this isuue?
A workaround can be to check explicitly if dispose had started and then return from the OnLostFocus. But I'd rather understans better what happens behind.
Thanks!
According to http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx, Microsoft suggested that OnEnter and OnLeave should be used instead of OnGotFocus and OnLostFocus.
The GotFocus and LostFocus events are
low-level focus events that are tied
to the WM_KILLFOCUS and WM_SETFOCUS
Windows messages. Typically, the
GotFocus and LostFocus events are only
used when updating UICues or when
writing custom controls. Instead the
Enter and Leave events should be used
for all controls except the Form
class, which uses the Activated and
Deactivate events. For more
information about the GotFocus and
LostFocus events, see the WM_SETFOCUS
and WM_KILLFOCUS topics in the
"Keyboard Input Reference" section in
the MSDN library at
http://msdn.microsoft.com/library.http://msdn.microsoft.com/library.

Arrow key events not arriving

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.

Categories

Resources