Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Setting a shortcut key in a form 1

Status
Not open for further replies.

timmay3141

Programmer
Dec 3, 2002
468
US
I want a certain method to be called whenever Ctrl+Left arrow is pressed when my form is active. It is easy to do this for menu items with their Shortcut property, but I can't figure out how to do it when there is no menu item corresponding to this. I can't just override OnKeyDown as I'd like to since it isn't ever called because a control has focus. I suppose I could create a menu item, hide it, and add a shortcut key to get this to work, but I really shouldn't have to do that. In C++ I could do this easily enough with an accelerator, but since C# is simpler, so I can't figure out how to do it :). Can anyone help?
 
Hi,

You can override the ProcessCmdKey method to capture the keystroke combination. You could also put the code in a new class to make it easier to reuse in the future.

Code:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
   const int WM_KEYDOWN = 0x100;
   Keys keyCode = (Keys)(msg.WParam.ToInt32() &
                  System.Convert.ToInt32(Keys.KeyCode));

   if ((msg.Msg == WM_KEYDOWN && keyCode == Keys.Left) &&
       (Control.ModifierKeys == Keys.Control))
   {
      // call the method
      MyMethod();
      return true;
   }
   else
   {
      return base.ProcessCmdKey (ref msg, keyData);
   }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top