Context Menu ShortcutKeys do not work C#

181 views Asked by At

I would like to add shortcuts to the MenuItems in my ContextMenu. I am using this code:

mnuContextMenu = new ContextMenu(); 
saveMenuItem = new MenuItem("Speichern", SaveFile, Shortcut.CtrlS); 
mnuContextMenu.MenuItems.Add(saveMenuItem); 

The Shortcut is even shown inside the ContextMenu, but it does not respond when i am pressing the keys.

Anybody has an idea why?

1

There are 1 answers

0
Mohammadreza Qorbanpur On

I solved this problem............. with the code below...

using System; using System.Windows.Forms;

namespace MyApp { public class Program : Form { private const int WM_HOTKEY = 0x0312; [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    
    public static void Main()
    {
        Application.Run(new Program());
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        // rej short key
        RegisterHotKey(Handle, 1, (int)ModifierKeys.Control | (int)ModifierKeys.Shift, Keys.F.GetHashCode());
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);

        // check msg
        if (m.Msg == WM_HOTKEY)
        {
            //short key
            int key = m.WParam.ToInt32();
            if (key == 1)
            {
                // 
                // example: this.Show();
            }
        }
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        //exit and free res
        UnregisterHotKey(Handle, 1);
        base.OnFormClosing(e);
    }

   
}

}