ComBoxHelper.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. namespace Common
  8. {
  9. public class ComBoxHelper
  10. {
  11. public static void ChangeString(object sender)
  12. {
  13. if (sender is TextBox)
  14. {
  15. TextBox tb = (TextBox)sender;
  16. for (int i = 0; i < tb.Text.Length; i++)
  17. {
  18. int isChange = 0;
  19. char newChar = FullCodeToHalfCode(tb.Text[i], ref isChange);
  20. if (isChange == 1)
  21. {
  22. tb.Text = tb.Text.Replace(tb.Text[i], newChar);
  23. tb.SelectionStart = i + 1;
  24. }
  25. }
  26. }
  27. else if (sender is ComboBox)
  28. {
  29. ComboBox cb = (ComboBox)sender;
  30. for (int i = 0; i < cb.Text.Length; i++)
  31. {
  32. int isChange = 0;
  33. char newChar = FullCodeToHalfCode(cb.Text[i], ref isChange);
  34. if (isChange == 1)
  35. {
  36. cb.Text = cb.Text.Replace(cb.Text[i], newChar);
  37. cb.SelectionStart = i + 1;
  38. }
  39. }
  40. }
  41. }
  42. public static char FullCodeToHalfCode(char c, ref int isChange)
  43. {
  44. //得到c的编码
  45. byte[] bytes = System.Text.Encoding.Unicode.GetBytes(c.ToString());
  46. int H = Convert.ToInt32(bytes[1]);
  47. int L = Convert.ToInt32(bytes[0]);
  48. //得到unicode编码
  49. int value = H * 256 + L;
  50. //是全角
  51. if (value >= 65281 && value <= 65374)
  52. {
  53. int halfvalue = value - 65248;//65248是全半角间的差值。
  54. byte halfL = Convert.ToByte(halfvalue);
  55. bytes[0] = halfL;
  56. bytes[1] = 0;
  57. isChange = 1;
  58. }
  59. else if (value == 12288)
  60. {
  61. int halfvalue = 32;
  62. byte halfL = Convert.ToByte(halfvalue);
  63. bytes[0] = halfL;
  64. bytes[1] = 0;
  65. isChange = 1;
  66. }
  67. else
  68. {
  69. isChange = 0;
  70. return c;
  71. }
  72. //将bytes转换成字符
  73. string ret = System.Text.Encoding.Unicode.GetString(bytes);
  74. return Convert.ToChar(ret);
  75. }
  76. }
  77. }