Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't detect a Ctrl + Key shortcut on keydown events whenever there's a readonly textbox with focus

Tags:

c#

.net

winforms

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? :(

like image 620
francis Avatar asked Jan 04 '11 17:01

francis


People also ask

What is KeyUp and KeyDown event?

KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.

What is KeyDown event in Visual Basic?

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.

Which of the following event is generated when the key is pushed down?

The keydown events happens when a key is pressed down, and then keyup – when it's released.

What is KeyDown C#?

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.


1 Answers

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.

like image 54
Don Kirkby Avatar answered Sep 20 '22 08:09

Don Kirkby