c#中設定快速鍵

來源:互聯網
上載者:User

最近找了一些資料,是講在C#中設定快速鍵運行方法或程式的

要設定快速鍵必須使用user32.dll下面的兩個方法。

BOOL RegisterHotKey(
 HWND hWnd,
 int id,
 UINT fsModifiers,
 UINT vk
);

  和

BOOL UnregisterHotKey(
 HWND hWnd,
 int id
);
轉換成C#代碼,那麼首先就要引用命名空間System.Runtime.InteropServices;來載入非託管類user32.dll。於是有了:

[DllImport("user32.dll", SetLastError=true)]
public static extern bool RegisterHotKey(
 IntPtr hWnd, // handle to window
 int id, // hot key identifier
 KeyModifiers fsModifiers, // key-modifier options
 Keys vk // virtual-key code
);

[DllImport("user32.dll", SetLastError=true)]
public static extern bool UnregisterHotKey(
 IntPtr hWnd, // handle to window
 int id // hot key identifier
);

[Flags()]
public enum KeyModifiers
{
 None = 0,
 Alt = 1,
 Control = 2,
 Shift = 4,
 Windows = 8
}

  這是註冊和卸載全域快速鍵的方法,那麼我們只需要在Form_Load的時候加上註冊快速鍵的語句,在FormClosing的時候卸載全域快速鍵。同時,為了保證剪貼簿的內容不受到其他程式調用剪貼簿的幹擾,在Form_Load的時候,我先將剪貼簿裡面的內容清空。

  於是有了:

private void Form1_Load(object sender, System.EventArgs e)
{
 label2.AutoSize = true;

 Clipboard.Clear();//先清空剪貼簿防止剪貼簿裡面先複製了其他內容
 RegisterHotKey(Handle, 100, 0, Keys.F10);
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
 UnregisterHotKey(Handle, 100);//卸載快速鍵
}

  那麼我們在別的視窗,怎麼讓按了快速鍵以後調用我的主過程ProcessHotkey()呢?

  那麼我們就必須重寫WndProc()方法,通過監視系統訊息,來調用過程:

protected override void WndProc(ref Message m)//監視Windows訊息
{
 const int WM_HOTKEY = 0x0312;//按快速鍵
 switch (m.Msg)
 {
  case WM_HOTKEY:
   ProcessHotkey();//調用主處理常式
   break;
 }
 base.WndProc(ref m);
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.