首页 > 解决方案 > 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 


    }
}

}

标签: c#winformseventsoverriding

解决方案


如果您有一组 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;
        }
    }

推荐阅读