在Visual C#程序中使用系統(tǒng)熱鍵

2010-08-28 10:52:01來源:西部e網(wǎng)作者:

  1.首先引入System.Runtime.InteropServices

using System.Runtime.InteropServices;

  2.在類內(nèi)部聲明兩個API函數(shù),它們的位置和類的成員變量等同.

[System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函數(shù)
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函數(shù)
public static extern bool UnregisterHotKey(
IntPtr hWnd, // handle to window
int id // hot key identifier
);

  3.定義一個KeyModifiers的枚舉,以便出現(xiàn)組合鍵

public enum KeyModifiers
{
 None = 0,
 Alt = 1,
 Control = 2,
 Shift = 4,
 Windows = 8
}

  4.在類的構(gòu)造函數(shù)出注冊系統(tǒng)熱鍵

  示例,下例注冊了四個熱鍵:

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()方法,通過監(jiān)視系統(tǒng)消息,來調(diào)用過程

  示例:

protected override void WndProc(ref Message m)//監(jiān)視Windows消息
{
 const int WM_HOTKEY = 0x0312; //如果m.Msg的值為0x0312那么表示用戶按下了熱鍵
 switch (m.Msg)
 {
  case WM_HOTKEY:
  ProcessHotkey(m); //按下熱鍵時調(diào)用ProcessHotkey()函數(shù)
  break;
 }
 base.WndProc(ref m); //將系統(tǒng)消息傳遞自父類的WndProc
}

  5.不用說,我們接下來需要實現(xiàn)ProcessHotkey函數(shù):

//按下設(shè)定的鍵時調(diào)用該函數(shù)
private void ProcessHotkey(Message m)
{
 IntPtr id = m.WParam; //IntPtr用于表示指針或句柄的平臺特定類型
 //MessageBox.Show(id.ToString());
 string sid = id.ToString();
 switch (sid)
 {
  case "100": DecreseVolumnb(); break; // 按下Control +光標左箭頭,調(diào)用函數(shù)DecreseVolumnb();
  case "200": AddVolumnb(); break; // 按下Control +光標右箭頭,調(diào)用函數(shù)AddVolumnb()
  case "300":// 按下Control +光標上箭頭,顯示窗體
   this.Visible = true;
   break;
  case "400":// 按下Control +光標下箭頭,隱藏窗體
   this.Visible = false;
   break;
 }
}

  很明顯接下來分別實現(xiàn)函數(shù)DecreseVolumnb(); 和AddVolumnb(); 即可.

  6.最后別忘了在程序退出時取消熱鍵的注冊

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
 UnregisterHotKey(Handle, 100); //卸載第1個快捷鍵
 UnregisterHotKey(Handle, 200); //缷載第2個快捷鍵
 UnregisterHotKey(Handle, 300); //卸載第3個快捷鍵
 UnregisterHotKey(Handle, 400); //缷載第4個快捷鍵
}

  以上就是在C#程序中使用系統(tǒng)熱鍵的整個過程。

關(guān)鍵詞:C#

贊助商鏈接: