简体   繁体   中英

How to prevent user control from stealing focus?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM