I'm working on a MDI
winforms project, I want to user uses F3 shortcut to open a search form in every where in application, so I used following code in my MDI
parent form and set the parent form's KeyPreview
to true
:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.F3)) {
//Show search form
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
The shortcut works in MDI
parent and child forms, but If I open a form from one of MDI
child forms using .ShowDialog()
the shortcut doesn't work in last form, in the other word, the shortcut, works in childForm
:
//in the parent form
var childForm = new Form1();
childForm.MdiParent = parentForm;
childForm.KeyPreview = true;
childForm.Show();
but doesn't work in grandChildForm
form:
//in the child form
var grandChildForm = new Form2();
grandChildForm.KeyPreview = true;
grandChildForm.ShowDialog();
How can I solve the problem, without repeating ProcessCmdKey()
method in all forms?
Create a baseForm
:
public partial class baseForm : Form
{
public baseForm()
{
InitializeComponent();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.F3))
{
//Show search form
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
And let all your others forms inherit from it:
public partial class Form1 : baseForm
Then any common functionality you want can be added to baseForm.