技术开发 频道

在Visual C#程序中使用系统热键


【IT168技术文档】

  1.首先引入System.Runtime.InteropServices
using System.Runtime.InteropServices;
  2.在类内部声明两个API函数,它们的位置和类的成员变量等同.
[System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数 public static extern bool RegisterHotKey( IntPtr hWnd, // handle to window int id, // hot key identifier uint fsModifiers, // key-modifier options Keys vk // virtual-key code ); [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数 public static extern bool UnregisterHotKey( IntPtr hWnd, // handle to window int id // hot key identifier );
  3.定义一个KeyModifiers的枚举,以便出现组合键
public enum KeyModifiers {  None = 0,  Alt = 1,  Control = 2,  Shift = 4,  Windows = 8 }
  4.在类的构造函数出注册系统热键

  示例,下例注册了四个热键:
public MainForm() {  InitializeComponent();  RegisterHotKey(Handle, 100, 2, Keys.Left); // 热键一:Control +光标左箭头  RegisterHotKey(Handle, 200, 2, Keys.Right); / /热键一:Control +光标右箭头  RegisterHotKey(Handle, 300, 2, Keys.Up); // 热键一:Control +光标上箭头  RegisterHotKey(Handle, 400, 2, Keys.Down); // 热键一:Control +光标下箭头  ....; }
  5.重写WndProc()方法,通过监视系统消息,来调用过程

  示例:
protected override void WndProc(ref Message m)//监视Windows消息 {  const int WM_HOTKEY = 0x0312; //如果m.Msg的值为0x0312那么表示用户按下了热键  switch (m.Msg)  {   case WM_HOTKEY:   ProcessHotkey(m); //按下热键时调用ProcessHotkey()函数   break;  }  base.WndProc(ref m); //将系统消息传递自父类的WndProc }

0
相关文章