c# - 自定义文本框控件

标签 c# .net winforms custom-controls

<分区>

是否可以像这样在 Visual Studio 中创建文本框:

最佳答案

其实。更好的解决方案是简单地使用文本框的 Paint 事件来绘制字符串。

代码如下:

class CueTextBox : TextBox
{
    public event EventHandler CueTextChanged;
    private string _cueText;

    public string CueText
    {
        get { return _cueText; }
        set
        {
            value = value ?? string.Empty;
            if (value != _cueText)
            {
                _cueText = value;
                OnCueTextChanged(EventArgs.Empty);
            }
        }
    }

    public CueTextBox()
        : base()
    {
        _cueText = string.Empty;
    }

    protected virtual void OnCueTextChanged(EventArgs e)
    {
        this.Invalidate(true);
        if (this.CueTextChanged != null)
            this.CueTextChanged(this, e);
    }

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

        if (string.IsNullOrEmpty(this.Text.Trim()) && !string.IsNullOrEmpty(this.CueText) && !this.Focused)
        {
            Point startingPoint = new Point(0, 0);
            StringFormat format = new StringFormat();
            Font font = new Font(this.Font.FontFamily.Name, this.Font.Size, FontStyle.Italic);
            if (this.RightToLeft == RightToLeft.Yes)
            {
                format.LineAlignment = StringAlignment.Far;
                format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
            }
            e.Graphics.DrawString(CueText, font, Brushes.Gray, this.ClientRectangle, format);
        }
    }

    const int WM_PAINT = 0x000F;
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_PAINT)
        {
            this.OnPaint(new PaintEventArgs(Graphics.FromHwnd(m.HWnd), this.ClientRectangle));
        }
    }
}

现在,您只需将“CueText”属性设置为您想要的初始值即可!

关于c# - 自定义文本框控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9247756/

相关文章:

c# - 条件资源编译

c# - Regex.Replace 和静态上下文?

.net - F# 和 FsXaml 用于打开新的 xaml 窗口

.net - 禁用 TabControl 上的默认快捷方式

c# - Winforms:创建动态时间轴控件

C# XNA Xbox,本例可选参数不可选

c# - 为什么我必须在不需要时使用关键字 static?

c# - Convert.ToDecimal(string) 和 Decimal.Parse(string) 之间的区别

c# - 如何从 XmlNode 实例获取 xpath

c# - 当前上下文中不存在名称 'form'