C#中TextBox的横线样式及占位提示详解

  public partial class TextBoxP : TextBox

  {

  private const int EM_SETCUEBANNER = 0x1501;

  [DllImport("user32.dll", CharSet = CharSet.Auto)]

  private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);

  Panel panel = new Panel();

  public TextBoxP()

  {

  InitializeComponent();

  this.BorderStyle = BorderStyle.FixedSingle;

  this.Font = new Font("宋体", 12f);

  }

  private string _Placeholder;

  [Browsable(true)]

  [Description("设置提示信息")]

  public string Placeholder

  {

  get

  {

  return _Placeholder;

  }

  set

  {

  _Placeholder = value;

  SendMessage(Handle, EM_SETCUEBANNER, 0, _Placeholder);

  }

  }

  private bool _IsLineStyle;

  [Browsable(true)]

  [Description("设置以横线样式显示")]

  public bool IsLineStyle

  {

  get { return _IsLineStyle; }

  set

  {

  _IsLineStyle = value;

  SetLineStyle();

  }

  }

  private void SetLineStyle()

  {

  if (_IsLineStyle && !this.Controls.Contains(panel))

  {

  this.BorderStyle = BorderStyle.None;

  this.SuspendLayout();

  panel.Height = 1;

  panel.Width = this.Width;

  panel.BorderStyle = BorderStyle.FixedSingle;

  panel.Location = new Point(0, this.Height - 1);

  this.Controls.Add(panel);

  this.ResumeLayout();

  this.PerformLayout();

  this.SizeChanged += TextBoxP_SizeChanged;

  this.LocationChanged += TextBoxP_LocationChanged;

  }

  else if (!_IsLineStyle)

  {

  if (this.Controls.Contains(panel))

  {

  this.Controls.Remove(panel);

  }

  this.BorderStyle = BorderStyle.FixedSingle;

  this.SizeChanged -= TextBoxP_SizeChanged;

  this.LocationChanged -= TextBoxP_LocationChanged;

  }

  if (!string.IsNullOrWhiteSpace(_Placeholder))

  {

  SendMessage(Handle, EM_SETCUEBANNER, 0, _Placeholder);

  }

  }

  void TextBoxP_SizeChanged(object sender, EventArgs e)

  {

  panel.Width = this.Width;

  }

  void TextBoxP_LocationChanged(object sender, EventArgs e)

  {

  panel.Location = new Point(0, this.Height - 1);

  }

  }