设置全局快捷键
public partial class Form1 : Form { [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool RegisterHotKey( IntPtr hWnd, //要定义热键的窗口的句柄 int id, //定义热键ID(不能与其它ID重复) int fsModifiers, //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效 int vk //定义热键的内容 ); [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool UnregisterHotKey( IntPtr hWnd, //要取消热键的窗口的句柄 int id //要取消热键的ID ); enum KeyModifier // 按键枚举值 { None = 0, Alt = 1, Control = 2, Shift = 4, WinKey = 8 } public Form1() { InitializeComponent(); // 注册快捷键Shift+S, 设置id为1 RegisterHotKey(this.Handle, 1, (int)KeyModifier.Shift, Keys.S.GetHashCode()); // 注册快捷键Shift+A, 设置id为2 RegisterHotKey(this.Handle, 2, (int)KeyModifier.Shift, Keys.A.GetHashCode()); } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == 0x0312) // 如果m.Msg的值为0x0312那么表示用户按下了热键 { int id = m.WParam.ToInt32(); if (id == 1) { MessageBox.Show("1"); } else if (id == 2) { MessageBox.Show("2"); } } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { UnregisterHotKey(Handle, 1); //卸载第1个快捷键 UnregisterHotKey(Handle, 2); //缷载第2个快捷键 } }
把圈子变小,把语言变干净,把成绩往上提,把故事往心里收,现在想要的以后你都会有。