18 April 2015

.net - Keyboard input in custom controls

I'm working on a custom control in .net WinForms that allows the user to input characters when it is focused. So far so good, but there's also a button on the form that has a hotkey assigned. It's label is New &chapter, so whenever I press "ALT+C", it's OnClick event fires. However, I noticed that it also fires when I just press "C", and that of course conflicts with my custom control, which doesn't even receive the keystroke for "C" anymore. I also noticed this doesn't happen when I'm typing in a regular text box. After a lengthy search I found this hotkey behavour is by design, so I needed to find a workaround for my control. After some more searching I finally found this event that does te trick:
protected override bool IsInputChar(char charCode) {
  if (this.Focused) {
    return true;
  }
  else {
    return base.IsInputChar(charCode);
  }
}
I put this in my custom control, and all works well. "ALT+C" still works on the button, but "C" goes to my custom control.

No comments:

Post a Comment