C# capture main form keyboard events

前端 未结 4 1930
盖世英雄少女心
盖世英雄少女心 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 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");
            }
        }
    }
    

提交回复
热议问题