在C#程式中使用系統熱鍵的整個過程。

來源:互聯網
上載者:User
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
}

  5.不用說,我們接下來需要實現ProcessHotkey函數:

//按下設定的鍵時調用該函數

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 +游標左箭頭,調用函數DecreseVolumnb();
  case "200": AddVolumnb(); break; // 按下Control +游標右箭頭,調用函數AddVolumnb()
  case "300":// 按下Control +游標上箭頭,顯示表單
   this.Visible = true;
   break;
  case "400":// 按下Control +游標下箭頭,隱藏表單
   this.Visible = false;
   break;
 }
}

  很明顯接下來分別實現函數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#程式中使用系統熱鍵的整個過程。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.