C# winform 自定義控制項之TextBox改PromtedTextBox 類似html標簽里input標簽里的placeHolder屬性,控制項繼承TextBox,擁有一個描述提示信息的欄位_txtPlaceHolder,重寫了消息處理函數WndProc,如果windows送出來的消息是繪製控制項... ...
效果:


public sealed class MyCustomTextBox:TextBox { private const int WM_PAINT = 0x000F; private string _txtPlaceHolder=""; [Category("自定義屬性"), Description("文本框里的提示文字"), DefaultValue("請在此輸入"), Browsable(true)] public string TxtPlaceHolder { get { return _txtPlaceHolder; } set { if (value == null) throw new ArgumentNullException("value"); _txtPlaceHolder = value; this.Invalidate(); } } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_PAINT && !this.Focused && (this.TextLength == 0) && (_txtPlaceHolder.Length > 0)) { TextFormatFlags tff = (TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.Left | TextFormatFlags.Top | TextFormatFlags.NoPadding); using (Graphics g = this.CreateGraphics()) { Rectangle rect = this.ClientRectangle; rect.Offset(4, 1); TextRenderer.DrawText(g, _txtPlaceHolder, this.Font, rect, SystemColors.GrayText, tff); } } } }