使用user32.dll库(c#)回调已注册的热键
我尝试了以下教程: 但是在我注册热键之后,它被注册了,但是回调不起作用。 调用WndProc时,keyPressed.Msg不等于0x0312,即按键。 对于为已注册热键创建回调有什么建议吗 这是注册和注销热键的类:使用user32.dll库(c#)回调已注册的热键,c#,C#,我尝试了以下教程: 但是在我注册热键之后,它被注册了,但是回调不起作用。 调用WndProc时,keyPressed.Msg不等于0x0312,即按键。 对于为已注册热键创建回调有什么建议吗 这是注册和注销热键的类: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Inte
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
class Hotkey
{
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private IntPtr _hWnd;
public Hotkey(IntPtr hWnd)
{
this._hWnd = hWnd;
}
public enum fsmodifiers
{
Alt = 0x0001,
Control = 0x0002,
Shift = 0x0004,
Window = 0x0008
}
public void RegisterHotkeys()
{
RegisterHotKey(IntPtr.Zero, 1, (uint)fsmodifiers.Control, (uint)Keys.B);
}
public void UnregisterHotkeys()
{
UnregisterHotKey(IntPtr.Zero, 1);
}
}
}
当前回调如下所示:
protected override void WndProc(ref Message keyPressed)
{
if(keyPressed.Msg == 0x0312)
Console.WriteLine();
base.WndProc(ref keyPressed);
}
0x0312是windows中按键的值。
但是我在Console.WriteLine()中设置了一个断点,但它从未到达那里
这是一个windows窗体应用程序。调用本机函数RegisterHotKey(…)时,会丢失窗口句柄(hWnd)
试试这个:
class Hotkey
{
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private IntPtr _hWnd;
public Hotkey(IntPtr hWnd)
{
this._hWnd = hWnd;
}
public enum fsmodifiers
{
Alt = 0x0001,
Control = 0x0002,
Shift = 0x0004,
Window = 0x0008
}
public void RegisterHotkeys()
{
RegisterHotKey(this._hWnd, 1, (uint)fsmodifiers.Control, (uint)Keys.B);
}
public void UnregisterHotkeys()
{
UnregisterHotKey(this._hWnd, 1);
}
}
要获取windows窗体的句柄,请使用:
this.Handle
首先,我建议您重写以下帖子:包含足够的代码,以允许其他人重现问题。
@SimoneCifani edited。谢谢您,它成功了!问题是我使用了FindWindow()
函数,该函数使用特定的字符串来标识窗体的窗口,可能是我键入的错误this.Handle
对于获取当前窗口更好。