How to create a winform with buttons that will never attract keyboard focus

后端 未结 4 1186
死守一世寂寞
死守一世寂寞 2020-12-21 07:07

I have a few textboxes on my winform. I have a few buttons on it too. Now when I am typing on one such textbox and clicks a button, then the input focus is lost from the tex

相关标签:
4条回答
  • 2020-12-21 07:30

    Try creating your own button control that inherits from the standard one but turns off the Selectable style:

    public class ButtonEx : Button {
      public ButtonEx() {
        this.SetStyle(ControlStyles.Selectable, false);
      }
    }
    
    0 讨论(0)
  • 2020-12-21 07:34

    You could set focus to the text box on buttons click event handler like this:

    private void Button_Click(...)
    {
        FocusTextBox();
        // Do things...
    }
    
    private void FocusTextBox()
    {
        textBox.Focus();
    }
    
    0 讨论(0)
  • 2020-12-21 07:35

    Create custom Button class with Focusable property, set Focusable to false

    public class ButtonEx : Button
    {
        [DefaultValue(true)]
        public bool Focusable
        {
            get { return GetStyle(ControlStyles.Selectable); }
            set { SetStyle(ControlStyles.Selectable, value); }
        }
    }
    
    0 讨论(0)
  • 2020-12-21 07:39

    In your button click event handler(s), explicitly set focus to some other control. Pick any control that you believe would be sensible to gain focus after the button is pressed. For example, set focus to a TextBox, using code like this:

    textBox1.Focus();
    

    This will prevent your button from gaining focus when a button is clicked.

    In addition, set your button's TabStop property to false.

    The other answers suggesting you set the CanFocus property to false won't work because that property is read-only for buttons.

    0 讨论(0)
提交回复
热议问题