Reputation: 4811
I'm building a WinForms app which looks roughly like this:
There is a single Form, with a menu, toolbar, status bar, a navigation tree, a custom drawing canvas (which is a UserControl that accepts keyboard input and draws text and also renders a caret) and a Find panel which allows the user to search for text.
I'm having difficulty with getting these behaviors to work:
1) The accelerators on the Find Panel (e.g. 'c' for Match case and 'w' for Whole words) prevent those characters from being entered into the canvas, even when the canvas has focus.
2) Pressing ESC when the focus is anywhere but the canvas should return the focus to the canvas. In particular, this should work when the Find textbox has focus. Can this be done by hooking the keyboard at a single point rather than for each possible focused control?
Upvotes: 0
Views: 351
Reputation: 54532
In the case where you have multiple controls competing for the keyboard input, set the Forms KeyPreview Property
to True
in order to handle your KeyPress events in the Form's KeyPress event handler. You can then direct the keyboard input accordingly.
From above MSDN link:
Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.
See if something like this works for you, it still will allow you to do a simultaneous Alt + Accelerator Key but will set the focus back to the usercontrol if it had focus and the Alt was pressed:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (ActiveControl.Name == userControl11.Name )
{
if (e.Alt)
{
e.Handled = true;
userControl11.Focus();
}
}
}
Upvotes: 2