TextBoxWithPlaceHolder.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Drawing;
  3. using System.Windows.Forms;
  4. namespace UAS_MES_NEW.CustomControl.TextBoxWithIcon
  5. {
  6. public partial class TextBoxWithPlaceHolder : UserControl
  7. {
  8. //记录一个PlaceHolder,第一次对这个文本框赋的值
  9. string PlaceHolder1;
  10. public string PlaceHolder
  11. {
  12. get
  13. {
  14. return PlaceHolder1;
  15. }
  16. set
  17. {
  18. PlaceHolder1 = value;
  19. }
  20. }
  21. public override string Text
  22. {
  23. get
  24. {
  25. if (TextBox.Text == PlaceHolder1)
  26. {
  27. return "";
  28. }
  29. return TextBox.Text;
  30. }
  31. set
  32. {
  33. TextBox.Text = value;
  34. }
  35. }
  36. public delegate void OnTextChange(object sender, EventArgs e);
  37. public delegate void OnKeyDown(object sender, KeyEventArgs e);
  38. public event OnTextChange UserControlTextChanged;
  39. public event OnKeyDown UserControlOnKeyDown;
  40. public TextBoxWithPlaceHolder()
  41. {
  42. InitializeComponent();
  43. Load += TextBoxWithPlaceHolder_Load;
  44. }
  45. private void TextBoxWithPlaceHolder_Load(object sender, System.EventArgs e)
  46. {
  47. TextBox.Text = PlaceHolder1;
  48. TextBox.ForeColor = Color.Silver;
  49. }
  50. private void TextBox_Leave(object sender, System.EventArgs e)
  51. {
  52. //失去焦点的时候如果文本框存在内容就把文字变色
  53. TextBox.BackColor = Color.White;
  54. if (TextBox.Text == "")
  55. {
  56. TextBox.ForeColor = Color.Silver;
  57. TextBox.Text = PlaceHolder1;
  58. }
  59. }
  60. private void TextBox_Enter(object sender, System.EventArgs e)
  61. {
  62. TextBox.ForeColor = Color.Black;
  63. if (TextBox.Text == PlaceHolder1)
  64. {
  65. TextBox.Text = "";
  66. }
  67. else TextBox.ForeColor = Color.Black;
  68. }
  69. private void TextBox_TextChanged(object sender, EventArgs e)
  70. {
  71. UserControlTextChanged?.Invoke(sender, new EventArgs());
  72. }
  73. private void TextBox_KeyDown_1(object sender, KeyEventArgs e)
  74. {
  75. UserControlOnKeyDown?.Invoke(sender, e);
  76. }
  77. }
  78. }