c#所有winforms文本框和组合框事件的一个类,无需直接调用



当文本框或组合框获得焦点时,我想更改背景颜色和字体大小。我有23张表格和很多控件。我想要一个公共类的例子,它自动处理gotfocus事件并更改属性。我很初级你的专家意见很有价值提前感谢

namespace LiabraryClasses.Library

// General Events Handler Class
class GEVENTS 
{
public override void textBox_GotFocus(object sender, EventArgs e)
{
// Increase font size  and background color 

}
}

}

如果你有一组TextBox,你不想要它们的正常行为,但想要它们聚焦时的一些特殊行为,那么实现这一点的简单面向对象的方法是创建一个特殊的TextBox类,在聚焦时更改Font和BackColor。

public class MySpecialTextBox : TextBox
{
public Font FontIfFocussed {get; set;}            // TODO: assign default values
public Font FontIfNotFocussed {get; set;}
public Color BackColorIfFocussed {get; set;}
public color BackColorIfNotFocussed {get; set;}
protected override OnGotFocus(Eventargs e)
{
// TODO: set font size and background color of this TextBox
}
protected override OnLostFocus(Eventargs e)
{
// TODO: set font size and background color of this TextBox
}
}

通过这种方式,您可以在visual studio设计器中选择您想要的TextBox类型:普通的,或者改变颜色和喜好的。

但如果你真的想使用原始的TextBox类并更改它:

class MyWindow
{
private myTextBox;
private Font fontIfFocussed = ..
private Font FontIfNotFocussed = ...
private Color BackColorIfFocussed = ...
private color BackColorIfNotFocussed = ...
public MyWindow()
{
this.myTextBox = new TextBox();
this.fontIfFocussed = new Font(this.myTextBox.Font.FontFamily, 16);
this.backColorIfFocussed = Color.AliceBlue;
...
this.myTextBox.GotFocus += this.OnGotFocus();
}
public void OnGotFocus(object sender, EventArgs e)
{
if (sender as Control control != null)
{
control.Font = this.fontIfFocussed;
control.BackColor = this.backColorIfFocussed;
}
}

最新更新