PasswordKeyboardForm.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Runtime.InteropServices;
  11. namespace PTMedicalInsurance.Forms
  12. {
  13. public partial class PasswordKeyboardForm : Form
  14. {
  15. // 导入Windows API函数
  16. [DllImport("user32.dll")]
  17. private static extern IntPtr GetForegroundWindow();
  18. [DllImport("user32.dll")]
  19. private static extern IntPtr GetFocus();
  20. [DllImport("user32.dll")]
  21. private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
  22. private const uint WM_CHAR = 0x0102;
  23. private IntPtr _targetEditBox;
  24. public PasswordKeyboardForm(IntPtr targetEditBox)
  25. {
  26. InitializeComponent();
  27. _targetEditBox = targetEditBox;
  28. }
  29. public PasswordKeyboardForm()
  30. {
  31. InitializeComponent();
  32. }
  33. private void SendKeyToFocusedControl(char key)
  34. {
  35. IntPtr focusedHandle = GetFocus();
  36. if (focusedHandle != IntPtr.Zero)
  37. {
  38. SendMessage(focusedHandle, WM_CHAR, (IntPtr)key, IntPtr.Zero);
  39. }
  40. }
  41. // 处理按钮点击事件
  42. private void btn_1_Click(object sender, EventArgs e)
  43. {
  44. Button button = sender as Button;
  45. if (button != null)
  46. {
  47. // 使用 SendKeys 将按钮的文本发送到当前焦点控件
  48. SendKeys.Send(button.Text);
  49. }
  50. }
  51. // 处理删除按钮点击事件
  52. private void btn_delete_Click(object sender, EventArgs e)
  53. {
  54. SendKeys.Send("{BACKSPACE}");
  55. }
  56. // 处理关闭按钮点击事件
  57. private void btn_Exit_Click(object sender, EventArgs e)
  58. {
  59. this.Close(); // 关闭密码键盘
  60. }
  61. private void btn_OK_Click(object sender, EventArgs e)
  62. {
  63. SendTextToEditBox(sender.ToString());
  64. }
  65. // 将文本发送到目标编辑框
  66. private void SendTextToEditBox(string text)
  67. {
  68. if (_targetEditBox != IntPtr.Zero)
  69. {
  70. foreach (char c in text)
  71. {
  72. SendMessage(_targetEditBox, WM_CHAR, (IntPtr)c, IntPtr.Zero);
  73. }
  74. }
  75. }
  76. private void btn_clear_Click(object sender, EventArgs e)
  77. {
  78. SendKeys.Send("^{A}"); // 全选
  79. SendKeys.Send("{DEL}"); // 删除
  80. }
  81. private void PasswordKeyboardForm_Load(object sender, EventArgs e)
  82. {
  83. this.TopMost = true;
  84. }
  85. }
  86. }