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,只寫全球熱鍵代碼,它的工作!我怎樣才能解決你的想法? –