c# - 如何将 Font 保留在继承的 TextBox 中?

标签 c# .net winforms user-controls

我正在使用以下代码获取未绘制边框的 TextBox:

public partial class CustomTextBox : TextBox
{
    public CustomTextBox()
    {
        InitializeComponent();
        SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        int borderWidth = 1;

        ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle,
            Color.Transparent, borderWidth, ButtonBorderStyle.Solid,
            Color.Transparent, borderWidth, ButtonBorderStyle.Solid,
            Color.Transparent, borderWidth, ButtonBorderStyle.Solid,
            Color.Transparent, borderWidth, ButtonBorderStyle.Solid);
    }
}

我似乎错过了 OnPaint() 内部的某些内容,因为我的字体不再是文本框的默认字体(也许我必须覆盖另一个事件)。

当检查 CustomTextBox.Font 属性时,它显示默认的“Microsoft SansSerif in 8,25”,但是当在我的文本框中键入文本时,字体肯定看起来更大更粗。

希望你能帮助我!

问候,

创新

[编辑]

我应该提到,如果我不覆盖 OnPaint,我的 CustomTextBox 的字体是正确的。仅当覆盖 OnPaint 时我的字体不正确(键入文本时字体更大并且看起来是粗体)。 所以我想我必须做一些事情来在 OnPaint 中正确地初始化字体(但是 ATM 我不知道该怎么做)。

最佳答案

如果尚未创建文本框的句柄,请不要调用 SetStyle,它永远不会更改为“大粗体”字体:

if (IsHandleCreated)
{
     SetStyle(ControlStyles.UserPaint, true);
}

关于c# - 如何将 Font 保留在继承的 TextBox 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1222028/

相关文章:

c# - 在 C# 中使用 C++ CLI 模板类

winforms - Windows 窗体中的报表查看器 2010 文本框对齐问题

c# - 无法使用 Json.Net 序列化对象

c# - 请定义#define

c# - 无法使用反射获取泛型类型的属性

c# - 使用成员访问 lambda 表达式参数化 LINQ to SQL 谓词

.net - 如何最好地实现脏话处理程序(首选 .NET)?

c# - 如何在 Parse.com 上查找和更新记录

c# - UserControl.ParentForm 为空

c# - 有没有办法让 AuthorizeAttribute 响应状态代码 403 Forbidden 而不是重定向?