How to highlight the control when it gets focus?

风流意气都作罢 提交于 2019-12-06 08:22:38

sender will be the target of the event.

You could cast sender:

MaskedTextBox maskedTextBox = sender as MaskedTextBox;
if (maskedTextBox != null) { maskedTextBox.SelectAll(); }

Or in C# 7,

if (sender is MaskedTextBox maskedTextBox) 
{
    maskedTextBox.SelectAll();
} 

Another improvement is to use TextBoxBase and it will work with TextBox and RichTextBox as well.

Put the following code in the form's constructor:

        foreach (Control c in Controls)
        {
            if (c is TextBox)
            {
                TextBox tb = c as TextBox;
                tb.GotFocus += delegate { tb.SelectAll(); };
            }
        }

Simply do that:

private void maskedTextBox1_Enter(object sender, EventArgs e)
{
   this.BeginInvoke((MethodInvoker) delegate() {
   maskedTextBox1.SelectAll();
   });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!