首页 > 解决方案 > OnPaint 文本框问题 -

问题描述

在 TextBox 上使用 OnPaint 事件时遇到问题。每当我用鼠标单击文本区域或开始键入时,文本框的背景都会变回白色。知道是什么原因造成的吗?

在此处输入图像描述

这是我的代码:

    protected override void OnCreateControl() {
        base.OnCreateControl();
        SetStyle(ControlStyles.OptimizedDoubleBuffer
            | ControlStyles.DoubleBuffer 
            | ControlStyles.AllPaintingInWmPaint
            | ControlStyles.ResizeRedraw
            | ControlStyles.UserPaint, true);
    }

    protected override void OnPaintBackground(PaintEventArgs e) {
        SolidBrush bBrush = new SolidBrush(Enabled ? BackColor : Color.LightGray);
        e.Graphics.FillRectangle(bBrush, ClientRectangle);
        bBrush.Dispose();
    }

    protected override void OnPaint(PaintEventArgs e) {
        base.OnPaint(e);
        using (Brush aBrush = new SolidBrush(ForeColor)) {
            StringFormat sf = new StringFormat();
            switch (TextAlign) {
                case HorizontalAlignment.Center:
                    sf.Alignment = StringAlignment.Center;
                    break;
                case HorizontalAlignment.Left:
                    sf.Alignment = StringAlignment.Near;
                    break;
                case HorizontalAlignment.Right:
                    sf.Alignment = StringAlignment.Far;
                    break;
            }
            string text = UseSystemPasswordChar && !Enabled
                ? new StringBuilder(Text.Length).Insert(0, PasswordChar.ToString(), Text.Length).ToString()
                : Text;
            e.Graphics.DrawString(text, (Font)Font.Clone(), aBrush, ClientRectangle, sf);
            aBrush.Dispose();
        }
    }

标签: c#winforms

解决方案


推荐阅读