How to create a Button that can send keys to a conrol without losing focus - Virtual Keyboard

后端 未结 1 1515
名媛妹妹
名媛妹妹 2020-11-27 23:40

How can I make a button that can sendkeys into a datagridview (so I need to somehow return datagridview to its state prior to it losing focus)

I\'ll explain the pro

相关标签:
1条回答
  • 2020-11-28 00:24

    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.

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