How to create a Button that can send keys to a control without stealing the focus – Virtual Keyboard

Non-Selectable Button to Send Key like Virtual Keyboard

It’s enough to make a non-selectable button and then handle it’s click event and send key. This way these buttons can work like virtual keyboard keys and the focus will remain on the control which has focus while it sends the key to the focused control.

public class ExButton:Button
{
    public ExButton()
    {
        SetStyle(ControlStyles.Selectable, false);
    }
}

Then handle click event and send key:

private void exButton1_Click(object sender, EventArgs e)
{
    SendKeys.SendWait("A");
}

SetStyle extension method for a Control

Is there any way of calling SetStyle on a Control without using
inheritance?

Yes, using Reflection, there is. Create this extension method:

public static class Extensions
{
    public static void SetStyle(this Control control, ControlStyles flags, bool value)
    {
        Type type = control.GetType();
        BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
        MethodInfo method = type.GetMethod("SetStyle", bindingFlags);
        if (method != null)
        {
            object[] param = { flags, value };
            method.Invoke(control, param);
        }
    }
}

Then use it this way, in your form Load event:

this.button1.SetStyle(ControlStyles.Selectable, false);

Then button1 will be non-selectable without inheritance.

Leave a Comment