更改边框颜色文本框在C# [英] Change border color in TextBox C#

查看:141
本文介绍了更改边框颜色文本框在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public class OurTextBox : TextBox
{
    public OurTextBox()
        : base()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
         base.OnPaint(e);
         Pen penBorder = new Pen(Color.Gray, 1);
         Rectangle rectBorder = new Rectangle(e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
         e.Graphics.DrawRectangle(penBorder, rectBorder);
   }
}

这是工作完美,但它并没有显示直到它得到焦点的文本。

This is working perfect, but it doesn't show the text until it gets focus.

任何人可以帮助我吗?什么是错的?

Can anybody help me? What is wrong?

感谢在前进。

推荐答案

您有绘制文本以及手动。

You have to draw text manually as well.

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Pen penBorder = new Pen(Color.Gray, 1);
    Rectangle rectBorder = new Rectangle(e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
    e.Graphics.DrawRectangle(penBorder, rectBorder);

    Rectangle textRec = new Rectangle(e.ClipRectangle.X + 1, e.ClipRectangle.Y + 1, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
    TextRenderer.DrawText(e.Graphics, Text, this.Font, textRec, this.ForeColor, this.BackColor, TextFormatFlags.Default);
}



另外,您可以尝试使用 e.Graphics。的DrawString()方法,如果 TextRenderer 是不是给你想要的结果(我总是有这种方法你更好的结果)。

Alternatively you can try to use e.Graphics.DrawString() method if TextRenderer is not giving you desired results (I always have better results with this approach thou).

这篇关于更改边框颜色文本框在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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