Reputation: 184
I am working on a Winform application in C#. I have a from frmPlan.frm and on that form I have some buttons/textboxes and a panel control. When that form load we load another form frmPlanDetail.frm inside that panel.
Now on that frmPlanDetail form we have a tab control and I was trying to implement hotkeys to navigate between tabs. I was able to implement the hotkeys by overriding the ProcessCmdKey event in frmPlanDetail.frm. But the problem that I am facing is it does not work untill I click on that tab control first. Once I click that control to set the focus it works after that but not after I load the form initially because at that time focus is on frmPlam form. I am using the following code for hot keys
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Alt | Keys.P))
{
tabCtrlIPE.SelectedIndex = 3;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Any help would be really appreciated.
Upvotes: 0
Views: 1713
Reputation: 709
The simplest way to handle hot keys is to add a MenuStrip, add a MenuItem and assign it your hot key (Alt + P in your case) and make the Visibility of the MenuItem as false. Now wire-up the menu item click event to do what you wanted to do.
Eventhough the menu is invisible, it would trigger the click event on pressing the hotkey.
I consider this as a straight-forward way for implementing hot keys as you don't have to deal with the control on which to handle key-press event, and adding your if-else ladders or switch statements.
Upvotes: 1
Reputation: 63317
It works OK for me when you place the code in the Top level parent (the outermost form):
public partial class Form1 : Form {
public Form1(){
InitializeComponent();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Alt | Keys.P)) {
tabCtrlIPE.SelectedIndex = 3;
return true;//Prevent beep sound
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Upvotes: 0