i thought i solved this problem by myself but it came back to haunt my application so here it goes:
i have the following keydown event handler registered in a form with a couple of disabled and readonly textboxes and they are only simple shortcuts for the buttons:
private void AccountViewForm_KeyDown(object sender, KeyEventArgs e)
{
//e.SuppressKeyPress = true;
//e.Handled = true;
if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.E && !isInEditMode)
btnEditMode_Click(sender, e);
if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.S && isInEditMode) btnEditMode_Click(sender, e);
if (e.KeyCode == Keys.Escape) btnCancel_Click(sender, e);
if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.W) Close();
}
the form has KeyPreview set to true but whenever a readonly textbox has focus and i press Ctrl + E i can't get "Control.ModifierKeys == Keys.Control" and "e.KeyCode == Keys.E" to be both true at the same time. What is really strange is that Ctrl + W works. Anyone has any idea what the hell is going on? :(
KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.
The KeyDown event occurs when the user presses a key while a form or control has the focus. This event also occurs if you send a keystroke to a form or control by using the SendKeys action in a macro or the SendKeys statement in Visual Basic.
The keydown events happens when a key is pressed down, and then keyup – when it's released.
KeyDown Event : This event raised as soon as the user presses a key on the keyboard, it repeats while the user keeps the key depressed. KeyUp Event : This event is raised after the user releases a key on the keyboard.
According to this question and this one, It looks like a more general way to handle keyboard shortcuts is to override the ProcessCmdKey() method:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.F)) {
MessageBox.Show("What the Ctrl+F?");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Have you considered using Alt + E and Alt + S and just setting the mnemonic property for your buttons? That seems to work well for me, and it's easier to set up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With