I’ve created a user control which has multiple textboxes, comboboxes etc. The user control is hosted on a normal form. I would like to assign keyboard short cuts to the text boxes, comboboxes. So that when Ctrl + F are pressed together the focus is placed on the one of the text boxes. I’ve tried using the OnPreviewKeyDown to examine the keys and then fire the key down method on the user control. The debugger doesn’t even hit the OnPreviewKeyDown method on the form. I’ve enabled keyPreview on the form to be true. I’ve provided some of my experiments below.
Can anyone point out where I’m going wrong? I can’t believe something like this is so difficult. I must be missing something simple. Thanks
protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
{
Keys k = e.KeyCode;
UserControl1.UserControl_KeyPress(k);
}
public void UserControl_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 'F')
tbxHostName.Focus();
switch (e.KeyCode)
{
case Keys.F:
this.cmbxProtocol.Focus();
break;
case Keys.H:
this.tbxHostName.Focus();
break;
default:
break;
}
}
I recommend trying the KeyDown Event. It takes in a KeyEventArgs parameter, which includes a boolean specifically for the Ctrl key (KeyEventArgs.Control).
In your case, you would compare the KeyCode property to Keys.F to see if
Fwas pressed, and check ifControlwas true. For example:Alternately, if you really want to stick with your
KeyPressevent, you could check the value of the static Control.ModifierKeys property and see if the Ctrl key is pressed, like so: