C# – Can’t detect a Ctrl + Key shortcut on keydown events whenever there’s a readonly textbox with focus

cnetwinforms

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? 🙁

Best Answer

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.

Related Topic