SearchBox.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Drawing;
  3. using System.Windows.Forms;
  4. namespace FastReport.Controls
  5. {
  6. internal class SearchBox : TextBoxButton
  7. {
  8. private string emptyText;
  9. private string saveText;
  10. public string EmptyText
  11. {
  12. get => emptyText;
  13. set
  14. {
  15. emptyText = value;
  16. if (TextBox.Text == "")
  17. TextBox.Text = value;
  18. }
  19. }
  20. public override string Text
  21. {
  22. get => TextBox.Text == EmptyText ? "" : TextBox.Text;
  23. set => TextBox.Text = value == "" ? EmptyText : value;
  24. }
  25. public event EventHandler Search;
  26. protected virtual void OnSearch(EventArgs e)
  27. {
  28. saveText = Text;
  29. Search?.Invoke(this, e);
  30. }
  31. private void textBox_GotFocus(object sender, EventArgs e)
  32. {
  33. if (TextBox.Text == EmptyText)
  34. TextBox.Text = "";
  35. saveText = Text;
  36. }
  37. private void textBox_LostFocus(object sender, EventArgs e)
  38. {
  39. var timer = new Timer() { Interval = 50, Enabled = true };
  40. timer.Tick += (s, args) =>
  41. {
  42. if (!Button.Focused)
  43. Text = saveText;
  44. timer.Dispose();
  45. };
  46. }
  47. private void textBox_KeyPress(object sender, KeyPressEventArgs e)
  48. {
  49. if (e.KeyChar == (char)13)
  50. {
  51. e.Handled = true;
  52. OnSearch(e);
  53. }
  54. else if (e.KeyChar == (char)27)
  55. {
  56. e.Handled = true;
  57. TextBox.Text = saveText;
  58. }
  59. }
  60. public SearchBox()
  61. {
  62. Button.BackColor = SystemColors.Window;
  63. ButtonClick += (s, e) =>
  64. {
  65. OnSearch(e);
  66. };
  67. TextBox.GotFocus += textBox_GotFocus;
  68. TextBox.LostFocus += textBox_LostFocus;
  69. TextBox.KeyPress += textBox_KeyPress;
  70. TextBox.PreviewKeyDown += (s, e) =>
  71. {
  72. if (e.KeyCode == Keys.Escape)
  73. e.IsInputKey = true;
  74. };
  75. }
  76. }
  77. }