C# capture main form keyboard events

前端 未结 4 1929
盖世英雄少女心
盖世英雄少女心 2020-12-20 17:10

How to catch keyboard events of the WinForm main form, where other controls are. So I want to catch one event Ctrl + S and doesn\'t matter where focus

相关标签:
4条回答
  • 2020-12-20 17:58

    You may add a MenuStrip and then create a menu strip item named save and give it a short cut Ctrl + S. Add a event handler for that. This will fire even if the focus is on other control on the form. If you don't like to see the MenuStrip; you can set visible = false too. I must admit this is ugly.

    0 讨论(0)
  • 2020-12-20 18:00

    the Form Class (System.Windows.Forms) has OnKeyDown, OnKeyPress, and OnKeyUp event methods that you can use to detect Ctrl + S

    use the KeyEventArgs in those methods to determine which keys were pressed

    EDIT

    be sure to enable Form.KeyPreview = true; so the form will capture the events regardless of focus.

    0 讨论(0)
  • 2020-12-20 18:07

    Try this code. Use the interface IMessageFilter you can filter any ctrl+key.

    public partial class Form1 : 
        Form,
        IMessageFilter
    {
        public Form1()
        {
            InitializeComponent();
    
            Application.AddMessageFilter(this);
            this.FormClosed += new FormClosedEventHandler(this.Form1_FormClosed);
        }
    
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.RemoveMessageFilter(this);
        }
    
        public bool PreFilterMessage(ref Message m)
        {
            //here you can specify  which key you need to filter
    
            if (m.Msg == 0x0100 && (Keys)m.WParam.ToInt32() == Keys.S &&
                ModifierKeys == Keys.Control) 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    

    I tested this and worked for me.

    0 讨论(0)
  • 2020-12-20 18:07

    Handle the KeyDown on the form and all its controls.

    private void OnFormLoad(object sender, EventArgs e)
    {
        this.KeyDown += OnKeyDown;
        foreach (Control control in this.Controls)
        {
            control.KeyDown += OnKeyDown;
        }
    }
    
    private void OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control)
        {
            if (e.KeyValue == (int)Keys.S)
            {
                Console.WriteLine("ctrl + s");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题