我对此进行了编码,之前它正在运行! 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);
}
有人有什么想法吗?
答案 0 :(得分: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);
}
}