How to set hotkeys for a Windows Forms form

后端 未结 8 1693
孤街浪徒
孤街浪徒 2020-12-03 05:22

I would like to set hotkeys in my Windows Forms form. For example, Ctrl + N for a new form and Ctrl + S for save. How would I do

8条回答
  •  既然无缘
    2020-12-03 05:43

    Set

    myForm.KeyPreview = true;
    

    Create a handler for the KeyDown event:

    myForm.KeyDown += new KeyEventHandler(Form_KeyDown);
    

    Example of handler:

        // Hot keys handler
        void Form_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.S)       // Ctrl-S Save
            {
                // Do what you want here
                e.SuppressKeyPress = true;  // Stops other controls on the form receiving event.
            }
        }
    

提交回复
热议问题