How do I create compound keyboard shortcuts in a Windows Forms application?

前端 未结 5 1390
执念已碎
执念已碎 2020-12-31 07:28

I want to create a component that allows us to have compound keyboard shortcuts associated with an arbitrary command, like the Visual Studio IDE and Microsoft Office do.

5条回答
  •  余生分开走
    2020-12-31 08:16

    Menu controls have property named ShortCut where you can assign a value. When you press that shortcut key, that menu item will be invoked. Use that property for the commands that has a corresponding menu.

    If you need shortcuts that won't be available on the menus, then you'll have to handle that your self via the KeyUp or KeyDown events, either on the form or the control. A KeyEventArgs object will be passed to your handler, and you can check which key is pressed, and whether the Ctrl, Alt or Shift keys were also pressed.

    Sample code from MSDN:

    // Handle the KeyDown event to determine the type of character entered into the control.
    private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        // Initialize the flag to false.
        nonNumberEntered = false;
    
        // Determine whether the keystroke is a number from the top of the keyboard.
        if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
        {
            // Determine whether the keystroke is a number from the keypad.
            if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
            {
                // Determine whether the keystroke is a backspace.
                if(e.KeyCode != Keys.Back)
                {
                    // A non-numerical keystroke was pressed.
                    // Set the flag to true and evaluate in KeyPress event.
                    nonNumberEntered = true;
                }
            }
        }
        //If shift key was pressed, it's not a number.
        if (Control.ModifierKeys == Keys.Shift) {
            nonNumberEntered = true;
        }
    }
    

提交回复
热议问题