c# - 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
}
}
}
解决方案
如果您有一组 TextBoxes,您不希望它们的正常行为但在它们获得焦点时会出现一些特殊行为,那么整洁的面向对象的方法是创建一个特殊的 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 Designer 中选择您想要的文本框类型:普通文本框,或者更改颜色和喜欢的文本框。
但是如果你真的想使用原来的 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;
}
}
推荐阅读
- python - 如何在 iMac 上的 IDLE 中清除屏幕?
- ios - 将应用上传到包含 firebase 的 AppStore
- angular - 从服务获取数据到组件订阅方法
- image - 使用 Gdrive 和 Gsheets 的座位计划
- point-clouds - 距离值深度图的点云
- excel-formula - 如何在没有逗号和分隔符的情况下分隔地址内容?(街道/城市/州/邮政编码)
- mongodb - 查询 ElemMatch 数组中的数组
- angular - 在不使用 Firebase 身份验证的情况下设置 Firestore 安全规则
- typescript - 如何将从后端服务获取的数据推送到 typescript 类中声明的属性中?
- ios - iOS:为什么 UIApplicationProtectedDataWillBecomeUnavailable 总是不通知?