Home > Net >  How to prevent MenuStrip from handling certain keys in WinForms?
How to prevent MenuStrip from handling certain keys in WinForms?

Time:03-09

I have a Form with a MenuStrip, where i want to react to "CTRL P" keystrokes.

The problem is, if the MenuStrip is opened, my Form doesnt get "CTRL P".

I tried setting Form's KeyPreview = true, and overriding ProcessCmdKey without success...

There is my ProcessCmdKey override:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control | Keys.P))
    {
        MessageBox.Show("ProcessCmdKey Control   P");
            return true;
    }
        return base.ProcessCmdKey(ref msg, keyData);
}

CodePudding user response:

The message doesn't go through the Form's key events and it will be handled by each dropdown.

You can use the approach which is mentioned in the comments, or as another option, you can implement IMessageFilter to capture the WM_KEYDOWN before it dispatches to the dropdown:

public partial class Form1 : Form, IMessageFilter
{
    const int WM_KEYDOWN = 0x100;
    public bool PreFilterMessage(ref Message m)
    {
        if (ActiveForm != this)
            return false;

        if (m.Msg == WM_KEYDOWN && 
            (Keys)m.WParam == Keys.P && ModifierKeys == Keys.Control)
        {
            MessageBox.Show("Ctrl   P pressed");
            return true;
        }
        return false;
    }
    protected override void onl oad(EventArgs e)
    {
        base.OnLoad(e);
        Application.AddMessageFilter(this);
    }
    protected override void OnClosing(CancelEventArgs e)
    {
        base.OnClosing(e);
        Application.RemoveMessageFilter(this);
    }
}
  • Related