設置快捷鍵(3種方式)
阿新 • • 發佈:2017-10-09
dll ebo con item id重復 缺點 controls ext 其它
(1)設置快捷鍵並顯示出來
MenuStrip ms = new MenuStrip(); ToolStripMenuItem tm1 = new ToolStripMenuItem("你好"); ToolStripMenuItem tl1 = new ToolStripMenuItem("你好1"); tl1.Click += Tl1_Click; tl1.ShowShortcutKeys = true; //tl1.ShortcutKeyDisplayString = "你好1的ShortcutKeyDisplayString"; 如果ShortcutKeyDisplayString為空,就顯示快捷鍵;反之顯示為ShortcutKeyDisplayString的值View Codetl1.ShortcutKeyDisplayString = null; tl1.ShortcutKeys = Keys.Control | Keys.A; tm1.DropDownItems.Add(tl1); ms.Items.Add(tm1); this.Controls.Add(ms); } private void Tl1_Click(object sender, EventArgs e) { MessageBox.Show("你好1的單擊事件"); }
(2)KeyDown事件
缺點:當程序失去焦點的時候這個熱鍵(快捷鍵)就不管用了!
private void TextBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.A) { //操作 } }View Code
(3)註冊和註銷系統熱鍵
①添加HotKey類
class HotKey { //如果函數執行成功,返回值不為0。 //如果函數執行失敗,返回值為0。要得到擴展錯誤信息,調用GetLastError。 [DllImport("user32.dll", SetLastError = true)] public static extern bool RegisterHotKey( IntPtr hWnd, //要定義熱鍵的窗口的句柄 int id, //定義熱鍵ID(不能與其它ID重復) KeyModifiers fsModifiers, //標識熱鍵是否在按Alt、Ctrl、Shift、Windows等鍵時才會生效 Keys vk //定義熱鍵的內容 ); [DllImport("user32.dll", SetLastError = true)] public static extern bool UnregisterHotKey( IntPtr hWnd, //要取消熱鍵的窗口的句柄 int id //要取消熱鍵的ID ); //定義了輔助鍵的名稱(將數字轉變為字符以便於記憶,也可去除此枚舉而直接使用數值) [Flags()] public enum KeyModifiers { None = 0, Alt = 1, Ctrl = 2, Shift = 4, WindowsKey = 8 } }View Code
②設置快捷鍵和事件
private void Form1_Activated(object sender, EventArgs e) { HotKey.RegisterHotKey(Handle, 100, HotKey.KeyModifiers.Ctrl, Keys.A);//註冊事件 100隨意寫,保證不重復。 } private void Form1_Leave(object sender, EventArgs e) { HotKey.UnregisterHotKey(Handle, 100);//註銷事件 } protected override void WndProc(ref Message m) { switch (m.WParam.ToInt32()) { case 100: MessageBox.Show("???");//執行事件 break; default: break; } base.WndProc(ref m); }View Code
完!
設置快捷鍵(3種方式)