问题
Steps to reproduce in VS Express 12:
- Create a new Windows Forms Application project
- Add a button
- Set the Form KeyPreview to true
- Add a keyDown event to the form
- The event will not trigger as long as the button is present on the form
I have a project where I want to catch both keydown and keyup events, however, I can only seem to get the keyup event to work.
I have a form with a single panel, button and label on it. In the form the keyPreview property is set to true, and is linked to both the KeyDown and KeyUp events. However, when I run the program, only the KeyUp event triggers.
I tried adding the event handlers manually by adding
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
But it still does not work.
Any suggestions?
KeyUp event:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
TriggerKey(e.KeyCode, false);
}
private void TriggerKey(Keys e, Boolean pKeyDown)
{
switch (e)
{
case Keys.Left:
mLeft = pKeyDown;
break;
case Keys.Right:
mRight = pKeyDown;
break;
case Keys.Down:
mDown = pKeyDown;
break;
case Keys.Up:
mUp = pKeyDown;
break;
}
}
My Form1_KeyDown event looks like this:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
TriggerKey(e.KeyCode, true);
}
Edit2: I've tried removing the button from my form, and then both events trigger correctly. If I add it back in, the keyDown event stops working again. Why is the button interfering when the keypreview property is set?
回答1:
KeyPreview is a VB6 compatibility feature, it isn't "native" Winforms. And it has a problem that exactly matches your issue. There are other Form methods that get a sniff at the keystroke first, before the code that looks at KeyPreview gets a chance to run and fire the KeyDown event. And they eat the navigation keystrokes first. Like the cursor keys that you are trying to see as well as the Tab key. This matches the VB6 behavior, it also couldn't see the cursor keys.
To stay ahead of that code, you'll need to override the ProcessDialogKey() method of the form. Like this:
protected override bool ProcessDialogKey(Keys keyData) {
switch (keyData) {
case Keys.Left:
//...
return true;
}
return base.ProcessDialogKey(keyData);
}
回答2:
you're setting mUp on keyDown...? can you add all the related code context such as the mouse up event, also you may try to refresh, if you break does the even fire on key down?
回答3:
Note that keyup is raised after keydown(if you want your mUp to remain true)
回答4:
I saw in other similar posts that this could help
this.focus();
give it a try and let me know to keep looking for other ways
来源:https://stackoverflow.com/questions/18280976/button-prevents-keydown-event-from-triggering-even-with-keypreview-true