gpt4 book ai didi

c# - 使用全局热键 : Get key that was actually pressed

转载 作者:行者123 更新时间:2023-11-30 17:27:50 25 4
gpt4 key购买 nike

在我的 form 中,我注册了不同的热键。后来在执行过程中,我想知道实际上按下了哪个热键。我可以从哪里获取该信息?

在初始化期间注册:

public Form1()
{
this.KeyPreview = true;
ghk = new KeyHandler(Keys.F1, this);
ghk.Register();
ghk = new KeyHandler(Keys.F2, this);
ghk.Register();
InitializeComponent();
}

使用这个 KeyHandler 类:

public class KeyHandler
{
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

private int key;
private IntPtr hWnd;
private int id;

public KeyHandler(Keys key, Form form)
{
this.key = (int)key;
this.hWnd = form.Handle;
id = this.GetHashCode();
}

public override int GetHashCode()
{
return key ^ hWnd.ToInt32();
}

public bool Register()
{
return RegisterHotKey(hWnd, id, 0, key);
}

public bool Unregister()
{
return UnregisterHotKey(hWnd, id);
}
}

触发的方法:

protected override void WndProc(ref Message m)
{
if (m.Msg == Constants.WmHotkeyMsgId)
HandleHotkey(m);
base.WndProc(ref m);
}

这里我想区分两个热键:

private void HandleHotkey(Message m)
{
if(key == F1)
DoSomething
if(key == F2)
DoSomethingElse
}

最佳答案

您应该能够通过使用 id 知道实际的 key 。当您注册热键时,您会使用一个 ID、一个键和一个修饰符。按下热键时,Windows 会在回调中为您提供热键的 ID,而不是键和修饰符。

RegisterHotKey(Handle, id: 1, ModifierKeys.Control, Keys.A);
RegisterHotKey(Handle, id: 2, ModifierKeys.Control | ModifierKeys.Alt, Keys.B);
const int WmHotKey = 786;
if (msg.message != WmHotKey)
return;

var id = (int)msg.wParam;
if (id == 1) // Ctrl + A
{
}
else if (id == 2) // Ctrl + Alt + B
{
}

这是我写的一篇博客文章,其中包含为 WPF 应用程序注册热键的代码: https://www.meziantou.net/2012/06/28/hotkey-global-shortcuts

关于c# - 使用全局热键 : Get key that was actually pressed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54247322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com