How to register a keyboard shortcut (hot key) in a .NET Windows Forms Application

来源:互联网 发布:stm8 ubuntu 编辑:程序博客网 时间:2024/06/06 09:01

转自http://windowscoding.com/blogs/blake/archive/2009/05/19/how-to-register-a-keyboard-shortcut-hot-key-in-a-net-windows-forms-application.aspx

1. WPF solution

    public WindowMain()       {              InitializeComponent();                    this.InputBindings.Add(new InputBinding(MyAppCommands.SaveAll, new KeyGesture(Key.F2, ModifierKeys.Control)););             CommandBinding cb = new CommandBinding(MyAppCommands.SaveAll);             cb.Executed += SaveAllDocuments;            this.CommandBindings.Add(cb );       }                 private void SaveAllDocuments(object obSender, ExecutedRoutedEventArgs e)        {        }

 

2. ProcessCmdKey

  protected override bool ProcessCmdKey(ref Message message, Keys keys)        {               switch (keys)                {                        case Keys.F2 | Keys.Control:                       //Process action here.                      return false;                }          }

3.IMessageFilter

public class MyMainForm : System.Windows.Forms.Form, IMessageFilter{     const int WM_KEYDOWN = 0x100;     const int WM_KEYUP = 0x101;     public bool PreFilterMessage(ref Message m)     {         Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode;        if (m.Msg == WM_KEYDOWN && keyCode == Keys.Escape)        {             Console.WriteLine("Ignoring Escape..."); return true;         }                 return false;     }         private void MyMainForm_Load(object sender, System.EventArgs e)     {         Application.AddMessageFilter(this);    } }



 

原创粉丝点击