1

I believe a similar question to this has been asked before but none of the solutions have worked for me. I have some code that needs to run when the CTRL button and the "+" button are both pressed. I made sure to set the KeyPreview field to true on the parent forum. I've tried putting the following event handlers in the control's class but none have worked for me so far. When I press any key, the event is not caught:

private void PreviewControl_OnKeyDown(object sender, KeyEventArgs e){}
protected override OnKeyDown(KeyEventArgs e){}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData){}
user2481095
  • 2,024
  • 7
  • 22
  • 32
  • 1
    Your control will receive the key event only if it contains focus. If you want to trap a shortcut key using your user control without having focus, you can use [this trick](http://stackoverflow.com/a/38983624/3110834). – Reza Aghaei Jan 26 '17 at 00:05
  • 1
    If your control is something like a `PictureBox` and you want to make it selectable and then want to handle key events, make it selectable like [this(Preferred)](http://stackoverflow.com/a/38982186/3110834) or [this](http://stackoverflow.com/a/37792846/3110834). – Reza Aghaei Jan 26 '17 at 00:18
  • I tried implementing the (Preferred) one but I'm still having the same issue with it. I must be doing something completely wrong but I can't figure out what it is. – user2481095 Jan 26 '17 at 00:37
  • My mouse events for the control work fine (for example: protected override void OnMouseWheel(MouseEventArgs e){}). I confirmed that when I enter this event handler, this.ContainsFocus == true, which should mean that the control has focus. So I'm thinking the issue must be more than just having focus on the control. – user2481095 Jan 26 '17 at 00:46

1 Answers1

0

So I got it to work with the help from @Reza Aghaei. I used this(Preferred). Reza was right, the control wasn't actually getting focus, so I needed to add this code in order to give the control focus when you click on it. However, I was not able to use the OnKeyDown event handler. Instead I had to use the ProcessCmdKey(ref Message msg, Keys keyData){} within the control class for it to catch the key event.

Community
  • 1
  • 1
user2481095
  • 2,024
  • 7
  • 22
  • 32