自定义文本框控件

gjj*_*n97 4 .net c# custom-controls winforms

是否可以在Visual Studio中创建一个文本框,如下所示:

Nis*_*sim 15

其实.更好的解决方案是使用文本框的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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您只需将'CueText'属性设置为您想要的初始值,就可以了!

  • 我喜欢你的方法,尽管你应该总是调用`Dispose`方法来释放`FromHwnd`方法创建的图形和相关资源。所以我建议使用代码`using (Graphics g = Graphics.FromHwnd(m.HWnd)) { this.OnPaint(new PaintEventArgs(g, this.ClientRectangle)); }` (2认同)