Issue
Weird problem. We’ve got two forms: the main application window and a settings form. The main form has its KeyPreview set to true, and a method attached to its KeyUp event. This is so that the settings window can be opened with a key shortcut (ctrl-m):
private void MyShortcuts(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.M)
{
e.Handled = true;
e.SuppressKeyPress = true;
MySettings sett = new MySettings();
sett.Show();
}
}
Now, that bit works just fine. However, the problem is that despite setting the Handled and SuppressKeyPress properties to true, the KeyUp event is still passed on to the MySettings form. I’ve traced this to ControlNativeWindow.OnMessage receiving what seems to be a different event (its Handled and SuppressKeyPress properties are set to false), and passing that on to the form and its focused control.
Questions
- First of all, why is the event passed on despite instructing .Net not to do so?
- Secondly, how do I prevent the event from firing?
Any ideas will be much appreciated, I run out of them myself.
What’s happening here is that the
Mand theCTRLkey are raising two separateKeyUpevents (which is normal behavior). When you pressCTRLand thenMand then lift your finger off of theMkey, aKeyUpevent is raised, which your handler on the main form catches and uses to show the settings form. You then take your finger off of theCTRLkey, which raises anotherKeyUpevent (this time on the settings form, which is now the active form).On the settings form, you can just check
e.Controland ignore the event if it’strue.