0
我创建了一个全局热键,首先它工作得很好。但是当我开始在表单和额外的代码中添加一些设计时,它不再适用。然后,我回到基础知识,只是将代码添加到原始代码中,但仍然没有运气。继承人的代码:c#修复了全局热键
热键类代码: 类热键 {
public enum fsModifers
{
Alt = 0x0001,
Control = 0x0002,
Shift = 0x0004,
Window = 0x0008,
}
IntPtr hWnds;
public HotKeys(IntPtr hWnd)
{
this.hWnds = hWnd;
}
public void RegisterHotKeys()
{
RegisterHotKey(hWnds, 1, (uint)fsModifers.Control, (uint)Keys.T);
RegisterHotKey(hWnds, 2, (uint)fsModifers.Control, (uint)Keys.R);
}
public void UnregisterHotKeys()
{
UnregisterHotKey(hWnds, 1);
UnregisterHotKey(hWnds, 2);
}
#region WindowsAPI
[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);
#endregion
}
主要形式的代码:(下面的代码只是相关热键的代码)
private void Form1_Load(object sender, EventArgs e)
{
thisWindow = FindWindow(null, "Form1");
_hotKeys = new HotKeys(thisWindow);
_hotKeys.RegisterHotKeys();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
_hotKeys.UnregisterHotKeys();
}
protected override void WndProc(ref Message keyPressed)
{
if (keyPressed.Msg == 0x0312)
{
MessageBox.Show("my msg");
//keyPress = keyPressed.WParam;
//if (keyPress == (IntPtr)1)
//{
// if (!autoSkillIsOn)
// {
// timer1.Start();
// autoSkillIsOn = true;
// }
// else if (autoSkillIsOn)
// {
// timer1.Stop();
// autoSkillIsOn = false;
// }
//}
//else if (keyPress == (IntPtr)2)
//{
// MessageBox.Show("pressed ctrl R");
//}
}
base.WndProc(ref keyPressed);
}
你可以在WndProc中看到我注释掉了我想要发生的事情,只是简单地写一个简单的messageBox,但猜测是什么,当按下任何注册的热键(Ctrl + T,Ctrl + R)时不会出现messageBox。为什么o为什么会发生?当代码仅仅是关于热键的时候,它在第一次工作就很好。感谢您的帮助!
它有点工作,然后运行应用程序后停止工作?过去我遇到过问题,你失去了触发按键事件的处理程序的引用?这是一个很长的一步,但是在保持对处理程序的引用处于活动状态方面,这可能是一个类似的问题吗? –
不工作了一下。当我运行它然后按注册键什么也没有发生。 –
@Joe_DM嘿男人我只是试图创建一个新的WinForm,只写全球热键代码,它的工作!我怎样才能解决你的想法? –