1.API申明
//註冊系統熱鍵
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(IntPtr hWnd, // handle to window
int id, // hot key identifier
KeyModifiers fsModifiers, // key-modifier options
Keys vk // virtual-key code
);
//解除註冊熱鍵
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(IntPtr hWnd, // handle to window
int id // hot key identifier
);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(IntPtr hWnd, // handle to window
int id, // hot key identifier
KeyModifiers fsModifiers, // key-modifier options
Keys vk // virtual-key code
);
//解除註冊熱鍵
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(IntPtr hWnd, // handle to window
int id // hot key identifier
);
2.定義並注冊熱鍵
[Flags()]
public enum KeyModifiers
{ //這是熱鍵的定義 alt+crtl是3 直接相加就可以了
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
private void MainForm_Load(object sender, System.EventArgs e)
{
//handle:這個窗體的handle 100:這個熱鍵的標誌id 3:crtl+alt鍵 H: h鍵
bool success = RegisterHotKey(Handle, 100, KeyModifiers.Control |
KeyModifiers.Alt, Keys.H);
}
public enum KeyModifiers
{ //這是熱鍵的定義 alt+crtl是3 直接相加就可以了
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
private void MainForm_Load(object sender, System.EventArgs e)
{
//handle:這個窗體的handle 100:這個熱鍵的標誌id 3:crtl+alt鍵 H: h鍵
bool success = RegisterHotKey(Handle, 100, KeyModifiers.Control |
KeyModifiers.Alt, Keys.H);
}
3.解除注冊熱鍵
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
//handle:這個窗體的handle 100:上面那個熱鍵的標誌id
UnregisterHotKey(Handle, 100);
}
{
//handle:這個窗體的handle 100:上面那個熱鍵的標誌id
UnregisterHotKey(Handle, 100);
}
4.根據熱鍵處理消息
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;//這個是window消息定義的 註冊的熱鍵消息
if (m.Msg == WM_HOTKEY)
{
if (m.WParam.ToString().Equals("100")) //如果是我們註冊的那個熱鍵
{
//這裡寫按下自寶義熱鍵後的代碼
}
}
base.WndProc(ref m);
}
{
const int WM_HOTKEY = 0x0312;//這個是window消息定義的 註冊的熱鍵消息
if (m.Msg == WM_HOTKEY)
{
if (m.WParam.ToString().Equals("100")) //如果是我們註冊的那個熱鍵
{
//這裡寫按下自寶義熱鍵後的代碼
}
}
base.WndProc(ref m);
}