如何获得焦点时突出显示控件? [英] How to highlight the control when it gets focus?

查看:201
本文介绍了如何获得焦点时突出显示控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下方法突出显示单个MaskedTextBox中的文本:

I can highlight the text in an individual MaskedTextBox when it gets focus using:

this.myTextBox.SelectAll();

但是,当发生鼠标单击事件时,我想对所有MaskedTextBox都执行此操作.我不想为每个MaskedTextbox添加30个单独的事件方法,而是要选择所有MaskedTextBox并有一个事件方法来处理它,即:

But, I want to do it for all MaskedTextBox when a mouse click event occurs. Instead of adding 30 individual event method for each MaskedTextbox, I want to select all MaskedTextBox and have one event method to take care of it, ie:

private void MouseClickedForMaskedTextBox(object sender, MouseEventArgs e)
{
    this.ActiveControl.SelectAll();
}

但是SelectAll不适用于this.ActiveControl.有办法解决吗?

But SelectAll is not available for this.ActiveControl. Is there a way to get around it?

推荐答案

sender将成为事件的目标.

您可以投射sender:

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

或者在C#7中,

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

另一个改进是使用TextBoxBase,它也可以与TextBoxRichTextBox一起使用.

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

这篇关于如何获得焦点时突出显示控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆