Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

c# - Register more than one hotkey with RegisterHotKey

I found this little piece of code to register an hotkey:

    [DllImport("user32.dll")]
    public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x0312)
            MessageBox.Show("Hotkey pressed");
        base.WndProc(ref m);
    }

    public FormMain()
    {
        InitializeComponent();
        //Alt + A
        RegisterHotKey(this.Handle, this.GetType().GetHashCode(), 1, (int)'A');
    }

It works perfectly, but my problem is I want to use two different shortcuts. I know the second parameter is the id, so I figure I could make a different id and add a new if statement in the WndProc function but I'm not sure how I would go about that.

In short, how would I go about creating a second shortcut?

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
 RegisterHotKey(this.Handle, this.GetType().GetHashCode(), 1, (int)'A')

Don't use GetHashCode() here. Just number your hot keys, start at 0. There isn't any danger of getting the ids mixed up, hot key ids are specific for each Handle. You'll get the id back in the WndProc() method. Use m.WParam.ToInt32() to get the value:

protected override void WndProc(ref Message m)
{
    if (m.Msg == 0x0312) {    // Trap WM_HOTKEY
        int id = m.WParam.ToInt32();
        MessageBox.Show(string.Format("Hotkey #{0} pressed", id));
    }
    base.WndProc(ref m);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...