1

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);
}
  • When a drop-down-menu is opened, it receives the input messages not the container (the `Form`) of the `xStrip` control. You need to handle the relevant key events of the drop-down-menus (all of them). A recursive method is required to get them and subscribe to their `KeyPress` or `KeyDown` events. [Something close](https://stackoverflow.com/questions/70731362/event-when-a-menu-item-is-highlighted/70733322#70733322). – dr.null Mar 08 '22 at 04:53

1 Answers1

1

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 OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        Application.AddMessageFilter(this);
    }
    protected override void OnClosing(CancelEventArgs e)
    {
        base.OnClosing(e);
        Application.RemoveMessageFilter(this);
    }
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398