0

我对此进行了编码,并且它更早地工作了!alt+1 和 alt+2 的全局热键。当我关闭我的项目时,我不小心按下了一个键或其他东西,现在由于某种原因只有 alt+1 正在工作,并且没有其他 alt+ 数字的组合......

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


    [DllImport("User32.dll")]
    private static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);
    [DllImport("User32.dll")]
    private static extern short GetAsyncKeyState(System.Int32 vKey);
    const int MYACTION_HOTKEY_ID = 1;

    public Form1()
    {
        InitializeComponent();
        RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, 1, (int)Keys.D1);
        RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, 1, (int)Keys.D2);
    }

    protected override void WndProc(ref Message m)
    {

        if (m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID && (GetAsyncKeyState(Keys.D1) == -32767))
        {
            Console.Write("alt+1");
        }
        if (m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID && (GetAsyncKeyState(Keys.D2) == -32767))
        {
            Console.Write("alt+2");
        }
        base.WndProc(ref m);
    }

有人有想法么?

4

1 回答 1

1

RegisterHotkey() 的第二个参数用于指定组合的 ID。每个组合都应该有自己的唯一 ID(至少对于与组合键关联的窗口句柄是唯一的)。当 ID 被传递给 WndProc() 中的 m.WParam 时,您可以知道按下了哪个热键。这是一个示例,其中 alt-1 的 ID 为 1001,而 alt-2 的 ID 为 1002:

public partial class Form1 : Form
{

    private const int WM_HOTKEY = 0x0312;
    private const int WM_DESTROY = 0x0002;

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

    public Form1()
    {
        InitializeComponent();
        RegisterHotKey(this.Handle, 1001, 1, (int)Keys.D1);
        RegisterHotKey(this.Handle, 1002, 1, (int)Keys.D2);
    }

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_HOTKEY:
                switch (m.WParam.ToInt32())
                {
                    case 1001:
                        Console.Write("alt+1");
                        break;

                    case 1002:
                        Console.Write("alt+2");
                        break;

                }
                break;

            case WM_DESTROY:
                UnregisterHotKey(this.Handle, 1001);
                UnregisterHotKey(this.Handle, 1002);
                break;
        }
        base.WndProc(ref m);
    }

}
于 2013-05-07T22:33:00.383 回答