程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> 在Visual C#程序中使用系統熱鍵

在Visual C#程序中使用系統熱鍵

編輯:關於C#

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#程序中使用系統熱鍵的整個過程。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved