利用win 32 API來達到熱鍵的效果
以下是程式的code,註解了幾個網站,供參考用
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices;//使用DLLImport需宣告 namespace hotkey { public partial class Form1 : Form { public Form1() { InitializeComponent(); } class HotKey//製作一個hotkey的class { [DllImport("user32.dll", SetLastError = true)] public static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk); //設定registerhotkey //相關資料http://msdn.microsoft.com/en-us/library/ms646309(VS.85).aspx [DllImport("user32.dll", SetLastError = true)] public static extern bool UnregisterHotKey(IntPtr hWnd, int id); //設定Unregisterhotkey //相關資料http://msdn.microsoft.com/en-us/library/ms646327(VS.85).aspx [Flags()]//設定 public enum KeyModifiers { None = 0, Alt = 1, Ctrl = 2, Shift = 4, WindowsKey = 8 } } protected override void WndProc(ref Message m) { //驗證用 //相關資料http://msdn.microsoft.com/zh-tw/library/dd229215.aspx const int WM_HOTKEY = 0x0312; switch (m.Msg) { case WM_HOTKEY: switch (m.WParam.ToInt32()) { case 100: this.button1.PerformClick(); //當case=100時,執行button1的內容 MessageBox.Show("100"); break; case 101: this.button2.PerformClick(); MessageBox.Show("101"); break; } break; } base.WndProc(ref m); } private void Form1_Activated(object sender, EventArgs e) { HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Shift, Keys.S); HotKey.RegisterHotKey(Handle, 101, HotKey.KeyModifiers.Shift, Keys.D); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("123"); } private void button2_Click(object sender, EventArgs e) { MessageBox.Show("123456"); } private void Form1_Leave(object sender, EventArgs e) { //當form leave時,執行UnregisterHotKey指令 HotKey.UnregisterHotKey(Handle, 100); HotKey.UnregisterHotKey(Handle, 101); } } }
最後感謝kloer的大力幫忙,解釋了一些不懂的地方...
再附上幾個網址
http://blog.blueshop.com.tw/hammerchou/archive/2006/10/16/42432.aspx
http://msdn.microsoft.com/en-us/library/ms646279(VS.85).aspx
若有錯誤請幫忙勘正..3Q
完畢收工....
沒有留言:
張貼留言