【发布时间】:2014-05-27 18:03:18
【问题描述】:
我目前正在将此代码用于热键管理器,这是我在此处的另一篇文章中找到的:
public class HotKeyReader
{
public static event EventHandler<HotKeyEventArgs> HotKeyPressed;
public static int RegisterHotKey(Keys key, KeyModifiers modifiers)
{
int id = System.Threading.Interlocked.Increment(ref _id);
RegisterHotKey(_wnd.Handle, id, (uint)modifiers, (uint)key);
return id;
}
public static bool UnregisterHotKey(int id)
{
return UnregisterHotKey(_wnd.Handle, id);
}
protected static void OnHotKeyPressed(HotKeyEventArgs e)
{
if (HotKeyReader.HotKeyPressed != null)
{
HotKeyReader.HotKeyPressed(null, e);
}
}
private static MessageWindow _wnd = new MessageWindow();
private class MessageWindow : Form
{
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_HOTKEY)
{
HotKeyEventArgs e = new HotKeyEventArgs(m.LParam);
HotKeyReader.OnHotKeyPressed(e);
}
base.WndProc(ref m);
}
private const int WM_HOTKEY = 0x312;
}
[DllImport("user32")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private static int _id = 0;
}
public class HotKeyEventArgs : EventArgs
{
public readonly Keys Key;
public readonly KeyModifiers Modifiers;
public HotKeyEventArgs(Keys key, KeyModifiers modifiers)
{
this.Key = key;
this.Modifiers = modifiers;
}
public HotKeyEventArgs(IntPtr hotKeyParam)
{
uint param = (uint)hotKeyParam.ToInt64();
Key = (Keys)((param & 0xffff0000) >> 16);
Modifiers = (KeyModifiers)(param & 0x0000ffff);
}
}
[Flags]
public enum KeyModifiers
{
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8,
NoRepeat = 0x4000
}
但是当一个热键被注册时,例如,只使用“a”,你不能再在 Windows 的其他任何地方使用“a”。有没有办法阻止这种情况发生?或者有没有更好的代码可以做到这一点。
【问题讨论】:
-
您希望 global 热键能做什么?
-
在 Mumble 等程序上,键盘快捷键可以在任何地方使用,并且不会独占使用。这就是我想要实现的目标。
-
你是什么意思他们“在任何地方工作”但“不独占使用”?这不是矛盾吗?你真的想要一个在你的程序中任何地方都可以使用的快捷方式吗?
-
我不使用那些程序。如果 Mumble 在后台运行,并且您在记事本中,并且按下分配给 Mumble 的热键,会发生什么?
-
假设我再次使用“a”,当我按下“a”时,Mumble 上会触发快捷方式,并且“a”会输入到记事本中。
标签: c# winforms hotkeys registerhotkey global-hotkey