How to create a winform with buttons that will never attract keyboard focus
I have multiple text boxes on my winform. I have several buttons on it. Now when I type one text box and click the button, the input focus is lost from the text box and the button gets the keyboard focus. That is, the cursor is lost from the text field at the moment when we press the button. I don't want this behavior. I want the cursor to persist in my textbox even when I click the button. The real situation is that I have text and number buttons that can only be used from a touch screen.
Try to create your own control that inherits from the standard one but disables the styling Selectable
:
public class ButtonEx : Button {
public ButtonEx() {
this.SetStyle(ControlStyles.Selectable, false);
}
}
In the event handler, click the Drawer button, explicitly set the focus to another control . Choose any control you think is reasonable for focusing after the button is pressed. For example, set focus to a TextBox using the following code:
textBox1.Focus();
This will prevent focus when the button is pressed.
Also, set the parameter TabStop
to false.
Other answers suggesting setting the property CanFocus
to false won't work because this property is read-only for buttons.
You can set focus to the textbox on buttons by clicking the event handler like this:
private void Button_Click(...)
{
FocusTextBox();
// Do things...
}
private void FocusTextBox()
{
textBox.Focus();
}
Create your own class Button
with property Focusable
, set Focusable
tofalse
public class ButtonEx : Button
{
[DefaultValue(true)]
public bool Focusable
{
get { return GetStyle(ControlStyles.Selectable); }
set { SetStyle(ControlStyles.Selectable, value); }
}
}