How to stop pressing button using keyboard keys like “Spacebar or Enter”. C#

前端 未结 3 1931
长发绾君心
长发绾君心 2020-12-22 01:09

I have win-foam application having several buttons. When i run this application, i am able to press these buttons using mouse click also able to press these buttons using ke

3条回答
  •  悲哀的现实
    2020-12-22 01:24

    The best I could work out for stopping all buttons responding to the space-bar is this:

    NB: It is a bit of a hack:

    Set your form's KeyPreview property to true.

    Then add this code to the form's KeyPress event:

    private void Form1_KeyPress(object sender, KeyPressEventArgs e) 
    {
       if (this.ActiveControl is Button
       && e.KeyChar == (char)Keys.Space) 
       {
          var button = this.ActiveControl;
          button.Enabled = false;
          Application.DoEvents();
          button.Enabled = true;
          button.Focus();
       }
    }
    

    And to stop a control from getting focus when tabbing, simply set the button's TabStop property to false.

提交回复
热议问题