Question

I created a user control that functions as a keyboard. I arranged the buttons in the control in the exact same manner as a keyboard, and set (ControlStyles.Selectable, false). This allows the focus to stay in a textbox that the user selected on the parent form. I also set the style of the user control to not be selectable. Everything works great when the user presses the buttons, but when the user control gets clicked, it steals the focus away from the textbox. Here is my code:

public partial class TouchKeyboard : UserControl
    {
        public TouchKeyboard()
        {
            InitializeComponent();
            SetStyle(ControlStyles.Selectable, false);

        }

        private void TouchKeyboard_Load(object sender, EventArgs e)
        {
            foreach (var button in this.Controls.OfType<CustomControls.CustomButton>())
            {
                button.Click += new EventHandler(this.ButtonClick);
            }
        }

        private void ButtonClick(object sender, EventArgs e)
        {
            var button = sender as CustomControls.CustomButton;

            if (button.Name == "btnSpace")
            {
                SendKeys.Send(" ");
            }
            else
            {
                SendKeys.Send("{" + button.Text + "}");
            }
        }
    }

Why would my user control steal focus when ControlStyles.Selectable is set to false?

Was it helpful?

Solution

After a few days of screwing with it, I finally figured it out. Since panels don't steal focus, I docked a panel in the User Control and placed my buttons inside it. That fixed the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top