TextControl.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows.Forms;
  7. using FWindSoft.SystemExtensions;
  8. using FWindSoft.Tools;
  9. namespace FWindSoft.WinForm
  10. {
  11. public class TextControl
  12. {
  13. private Control m_RefControl;
  14. public TextControl(Control ctrl)
  15. {
  16. m_RefControl = ctrl;
  17. TextBox textBox = ctrl as TextBox;
  18. if (textBox != null)
  19. {
  20. IsValid=true;
  21. Text=textBox.Text;
  22. SelectionStart=textBox.SelectionStart;
  23. SelectionLength=textBox.SelectionLength;
  24. return;
  25. }
  26. ComboBox cmb = ctrl as ComboBox;
  27. if (cmb != null)
  28. {
  29. IsValid=true;
  30. Text=cmb.Text;
  31. SelectionStart=cmb.SelectionStart;
  32. SelectionLength=cmb.SelectionLength;
  33. return;
  34. }
  35. }
  36. public bool IsValid{get;private set;}
  37. public Control RefControl { get { return this.m_RefControl; } }
  38. public string Text
  39. {
  40. get;private set;
  41. }
  42. public int SelectionStart
  43. {
  44. get;private set;
  45. }
  46. public int SelectionLength
  47. {
  48. get;private set;
  49. }
  50. /// <summary>
  51. /// 计算新的text
  52. /// </summary>
  53. /// <param name="ch">插入的c</param>
  54. /// <returns></returns>
  55. public string ClcNewText(char ch)
  56. {
  57. string strCurText = this.Text;
  58. if (SelectionLength <= 0)
  59. {
  60. strCurText = this.Text;
  61. strCurText = strCurText.Insert(this.SelectionStart, ch.ToString());
  62. }
  63. else
  64. {
  65. string a = strCurText.Substring(0, this.SelectionStart);
  66. string b = ch.ToString();
  67. string c = string.Empty;
  68. int intSelectIndex = this.SelectionStart + this.SelectionLength;
  69. if (intSelectIndex < strCurText.Length)
  70. {
  71. c = strCurText.Substring(intSelectIndex);
  72. }
  73. strCurText = a + b + c;
  74. }
  75. return strCurText;
  76. }
  77. /// <summary>
  78. /// 验证控件输入键盘事件之后是否为数字
  79. /// </summary>
  80. /// <param name="e">控件输入的键盘事件</param>
  81. /// <returns></returns>
  82. public bool ValidateNumeric(KeyPressEventArgs e)
  83. {
  84. do
  85. {
  86. if (e.KeyChar == (char)Keys.Back)
  87. {
  88. e.Handled = false;
  89. break;
  90. }
  91. if (!e.KeyChar.IsNumeric())
  92. {
  93. e.Handled = true;
  94. break;
  95. }
  96. string newString = this.ClcNewText(e.KeyChar);
  97. e.Handled = !RegexUtil.IsDecimalInputing(newString);
  98. } while (false);
  99. return !e.Handled;
  100. }
  101. }
  102. }