WinApi.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. using PTMedicalInsurance.Variables;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12. namespace PTMedicalInsurance.Common
  13. {
  14. class WinApi
  15. {
  16. private bool IsWindowExist(IntPtr handle)
  17. {
  18. return (!(GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero) && IsWindowVisible(new HandleRef(this, handle)));
  19. }
  20. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  21. public static extern IntPtr GetWindow(HandleRef hWnd, int uCmd);
  22. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  23. public static extern bool IsWindowVisible(HandleRef hWnd);
  24. /// <summary>
  25. /// 获取应用程序窗口句柄
  26. /// </summary>
  27. /// <param name="processId"></param>
  28. /// <returns></returns>
  29. private IntPtr GetWindowHandle(int processId)
  30. {
  31. var windowHandle = IntPtr.Zero;
  32. EnumThreadWindowsCallback windowsCallback = new EnumThreadWindowsCallback(FindMainWindow);
  33. EnumWindows(windowsCallback, IntPtr.Zero);
  34. //保持循环
  35. GC.KeepAlive(windowsCallback);
  36. bool FindMainWindow(IntPtr handle, IntPtr extraParameter)
  37. {
  38. int num;
  39. GetWindowThreadProcessId(new HandleRef(this, handle), out num);
  40. if (num == processId && IsWindowExist(handle))
  41. {
  42. windowHandle = handle;
  43. return true;
  44. }
  45. return false;
  46. }
  47. return windowHandle;
  48. }
  49. public delegate bool EnumThreadWindowsCallback(IntPtr hWnd, IntPtr lParam);
  50. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  51. public static extern bool EnumWindows(EnumThreadWindowsCallback callback, IntPtr extraData);
  52. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  53. public static extern int GetWindowThreadProcessId(HandleRef handle, out int processId);
  54. public static IntPtr GetWindowHandle(string name)
  55. {
  56. Process[] procs = Process.GetProcessesByName(name);
  57. if (procs.Length != 0)
  58. {
  59. return procs[0].MainWindowHandle;
  60. }
  61. return IntPtr.Zero;
  62. }
  63. public static IntPtr GetWindowsHandle(string WindowName)
  64. {
  65. IntPtr hwnd = IntPtr.Zero;
  66. Process[] procs = Process.GetProcessesByName(WindowName);
  67. if (procs.Length != 0)
  68. {
  69. hwnd = procs[0].MainWindowHandle;
  70. //MessageBox.Show("??" + procs[0].Id.ToString() + "??" + procs[0].MainWindowHandle.ToString());
  71. //Global.writeLog("GetWindowsHandle=>ProcessID:" + procs[0].Id + ",ManagedThreadId:" + Thread.CurrentThread.ManagedThreadId.ToString());
  72. //Global.writeLog("GetWindowsHandle=>CurrentProcessID:" + Process.GetCurrentProcess().Id);
  73. }
  74. //Process ps = procs[0];
  75. //Global.writeLog("Start");
  76. //for (int i = 0; i < ps.Threads.Count; i++)
  77. //{
  78. // var thread = ps.Threads[i];
  79. // string str = string.Empty;
  80. // str = str + "标识符(" + i.ToString() + "):"+ thread.Id.ToString() + System.Environment.NewLine;
  81. // //str = str + "标识符:" + thread. + System.Environment.NewLine;
  82. // str = str +"基本优先级:" + thread.BasePriority.ToString() + System.Environment.NewLine;
  83. // str = str +"当前优先级:" + thread.CurrentPriority.ToString() + System.Environment.NewLine;
  84. // str = str +"内存地址:" + thread.StartAddress.ToInt32() + System.Environment.NewLine;
  85. // str = str +"启动时间:" + thread.StartTime.ToString() + System.Environment.NewLine;
  86. // str = str +"使用时间:" + thread.UserProcessorTime.ToString() + System.Environment.NewLine;
  87. // str = str + "当前状态:";
  88. // switch (thread.ThreadState)
  89. // {
  90. // case System.Diagnostics.ThreadState.Initialized:
  91. // str = str +"线程已经初始化但尚未启动";
  92. // break;
  93. // case System.Diagnostics.ThreadState.Ready:
  94. // str = str +"线程准备在下一个可用的处理器上运行";
  95. // break;
  96. // case System.Diagnostics.ThreadState.Running:
  97. // str = str +"当前正在使用处理器";
  98. // break;
  99. // case System.Diagnostics.ThreadState.Standby:
  100. // str = str +"线程将要使用处理器";
  101. // break;
  102. // case System.Diagnostics.ThreadState.Terminated:
  103. // str = str +"线程已完成执行并退出";
  104. // break;
  105. // case System.Diagnostics.ThreadState.Transition:
  106. // str = str +"线程在可以执行钱等待处理器之外的资源";
  107. // break;
  108. // case System.Diagnostics.ThreadState.Unknown:
  109. // str = str +"状态未知";
  110. // break;
  111. // case System.Diagnostics.ThreadState.Wait:
  112. // str = str +"正在等待外围操作完成或者资源释放";
  113. // break;
  114. // default:
  115. // break;
  116. // }
  117. // if (thread.ThreadState == System.Diagnostics.ThreadState.Wait)
  118. // {
  119. // str = str + System.Environment.NewLine +"等待原因:";
  120. // switch (thread.WaitReason)
  121. // {
  122. // case ThreadWaitReason.EventPairHigh:
  123. // str = str +"线程正在等待事件对高";
  124. // break;
  125. // case ThreadWaitReason.EventPairLow:
  126. // str = str +"线程正在等待事件对低";
  127. // break;
  128. // case ThreadWaitReason.ExecutionDelay:
  129. // str = str +"线程执行延迟";
  130. // break;
  131. // case ThreadWaitReason.Executive:
  132. // str = str +"线程正在等待计划程序";
  133. // break;
  134. // case ThreadWaitReason.FreePage:
  135. // str = str +"线程正在等待可用的虚拟内存页";
  136. // break;
  137. // case ThreadWaitReason.LpcReceive:
  138. // str = str +"线程正在等待本地过程调用到达";
  139. // break;
  140. // case ThreadWaitReason.LpcReply:
  141. // str = str +"线程正在等待对本地过程调用的回复到达";
  142. // break;
  143. // case ThreadWaitReason.PageIn:
  144. // str = str +"线程正在等待虚拟内存页到达内存";
  145. // break;
  146. // case ThreadWaitReason.PageOut:
  147. // str = str +"线程正在等待虚拟内存页写入磁盘";
  148. // break;
  149. // case ThreadWaitReason.Suspended:
  150. // str = str +"线程执行暂停";
  151. // break;
  152. // case ThreadWaitReason.SystemAllocation:
  153. // str = str +"线程正在等待系统分配";
  154. // break;
  155. // case ThreadWaitReason.Unknown:
  156. // str = str +"线程因位置原因而等待";
  157. // break;
  158. // case ThreadWaitReason.UserRequest:
  159. // str = str +"线程正在等待用户请求";
  160. // break;
  161. // case ThreadWaitReason.VirtualMemory:
  162. // str = str +"线程正在等待系统分配虚拟内存";
  163. // break;
  164. // default:
  165. // break;
  166. // }
  167. // }
  168. // Global.writeLog("ThreadsInfo:" + procs[0].Id.ToString() + "_" + procs[0].ProcessName, "Count:" + ps.Threads.Count.ToString(), str);
  169. //}
  170. //Global.writeLog("End");
  171. //foreach (Process process in procs)
  172. //{
  173. // if (process.ProcessName.Contains(WindowName))
  174. // {
  175. // MessageBox.Show($"Process_Name = ({process.ProcessName}), Id = {process.Id}");
  176. // }
  177. //}
  178. //return GetCurrentWindowHandle((uint)procs[0].Id);
  179. //Process[] processes = Process.GetProcesses();
  180. //foreach (Process process in processes)
  181. //{
  182. // if (process.ProcessName.Contains(WindowName))
  183. // {
  184. // MessageBox.Show($"ProcessName = ({process.ProcessName}), Id = {process.Id}");
  185. // }
  186. //}
  187. return hwnd;
  188. }
  189. private static Hashtable processWnd = null;
  190. public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);
  191. //static User32API()
  192. //{
  193. // if (processWnd == null)
  194. // {
  195. // processWnd = new Hashtable();
  196. // }
  197. //}
  198. [DllImport("user32.dll", EntryPoint = "EnumWindows", SetLastError = true)]
  199. public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);
  200. [DllImport("user32.dll", EntryPoint = "GetParent", SetLastError = true)]
  201. public static extern IntPtr GetParent(IntPtr hWnd);
  202. [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
  203. public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);
  204. [DllImport("user32.dll", EntryPoint = "IsWindow")]
  205. public static extern bool IsWindow(IntPtr hWnd);
  206. [DllImport("user32.dll", EntryPoint = "EnableWindow")]
  207. public static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
  208. [DllImport("user32.dll", EntryPoint = "IsWindowEnabled")]
  209. public static extern bool IsWindowEnabled(IntPtr hWnd);
  210. [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
  211. public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
  212. [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
  213. public static extern bool SetForegroundWindow(IntPtr hWnd);
  214. [DllImport("user32.dll")]
  215. private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
  216. [DllImport("user32.dll")]
  217. private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
  218. [DllImport("user32.dll")]
  219. private static extern bool EnumChildWindows(IntPtr hWndParent, WNDENUMPROC lpEnumFunc, IntPtr lParam);
  220. private static IntPtr _comWindowHandle = IntPtr.Zero;
  221. private static string _comWindowTitle = "";
  222. /// <summary>
  223. /// 查找银海COM读卡窗口并置顶
  224. /// </summary>
  225. /// <param name="parentHwnd">父窗口句柄(当前窗体)</param>
  226. /// <returns>找到的窗口句柄</returns>
  227. public static IntPtr FindAndSetTopComWindow(IntPtr parentHwnd)
  228. {
  229. _comWindowHandle = IntPtr.Zero;
  230. _comWindowTitle = "";
  231. // 枚举当前窗体的子窗口
  232. EnumChildWindows(parentHwnd, (hwnd, lParam) =>
  233. {
  234. // 使用更大的缓冲区获取完整标题
  235. StringBuilder title = new StringBuilder(512);
  236. GetWindowText(hwnd, title, 512);
  237. string windowTitle = title.ToString().Trim();
  238. // 检查窗口是否可见
  239. if (!IsWindowVisible(new HandleRef(null, hwnd)))
  240. {
  241. return true; // 不可见窗口跳过
  242. }
  243. // 银海读卡窗口标题包含"社会保障卡"或"统一鉴权"
  244. if (windowTitle.Contains("社会保障卡") || windowTitle.Contains("统一鉴权") ||
  245. windowTitle.Contains("电子社保卡"))
  246. {
  247. _comWindowHandle = hwnd;
  248. _comWindowTitle = windowTitle;
  249. // 置顶窗口
  250. SetWindowPos(hwnd, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040); // SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW
  251. SetForegroundWindow(hwnd);
  252. return false; // 停止枚举
  253. }
  254. // 备选:按类名查找
  255. StringBuilder className = new StringBuilder(256);
  256. GetClassName(hwnd, className, 256);
  257. string[] yinhaiClassNames = { "YHCardReader", "YHCard", "CardReader", "ReadCard", "#32770" };
  258. foreach (var name in yinhaiClassNames)
  259. {
  260. if (className.ToString().Contains(name) || className.ToString().Contains("YH") || className.ToString().Contains("Card"))
  261. {
  262. _comWindowHandle = hwnd;
  263. _comWindowTitle = windowTitle;
  264. // 置顶窗口
  265. SetWindowPos(hwnd, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040);
  266. SetForegroundWindow(hwnd);
  267. return false; // 停止枚举
  268. }
  269. }
  270. return true; // 继续枚举
  271. }, IntPtr.Zero);
  272. return _comWindowHandle;
  273. }
  274. /// <summary>
  275. /// 查找银海COM读卡窗口并置顶(枚举系统所有窗口)
  276. /// </summary>
  277. /// <param name="parentHwnd">父窗口句柄(用于参考,可传0)</param>
  278. /// <returns>找到的窗口句柄</returns>
  279. public static IntPtr FindAndSetTopComWindowAll(IntPtr parentHwnd)
  280. {
  281. _comWindowHandle = IntPtr.Zero;
  282. _comWindowTitle = "";
  283. // 枚举系统中所有顶级窗口
  284. EnumWindows((hwnd, lParam) =>
  285. {
  286. // 使用更大的缓冲区获取完整标题
  287. StringBuilder title = new StringBuilder(512);
  288. GetWindowText(hwnd, title, 512);
  289. string windowTitle = title.ToString().Trim();
  290. // 检查窗口是否可见
  291. if (!IsWindowVisible(new HandleRef(null, hwnd)))
  292. {
  293. return true; // 不可见窗口跳过
  294. }
  295. // 银海读卡窗口标题包含"社会保障卡"或"统一鉴权"
  296. if (windowTitle.Contains("社会保障卡") || windowTitle.Contains("统一鉴权") ||
  297. windowTitle.Contains("电子社保卡"))
  298. {
  299. _comWindowHandle = hwnd;
  300. _comWindowTitle = windowTitle;
  301. // 置顶窗口
  302. SetWindowPos(hwnd, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040); // SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW
  303. SetForegroundWindow(hwnd);
  304. return false; // 停止枚举
  305. }
  306. // 备选:按类名查找
  307. StringBuilder className = new StringBuilder(256);
  308. GetClassName(hwnd, className, 256);
  309. string[] yinhaiClassNames = { "YHCardReader", "YHCard", "CardReader", "ReadCard" };
  310. foreach (var name in yinhaiClassNames)
  311. {
  312. if (className.ToString().Contains(name) || className.ToString().Contains("YH"))
  313. {
  314. _comWindowHandle = hwnd;
  315. _comWindowTitle = windowTitle;
  316. // 置顶窗口
  317. SetWindowPos(hwnd, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040);
  318. SetForegroundWindow(hwnd);
  319. return false; // 停止枚举
  320. }
  321. }
  322. return true; // 继续枚举
  323. }, IntPtr.Zero);
  324. return _comWindowHandle;
  325. }
  326. /// <summary>
  327. /// 获取最后找到的COM窗口标题
  328. /// </summary>
  329. public static string GetComWindowTitle()
  330. {
  331. return _comWindowTitle;
  332. }
  333. [DllImport("kernel32.dll", EntryPoint = "SetLastError")]
  334. public static extern void SetLastError(uint dwErrCode);
  335. public static IntPtr GetCurrentWindowHandle()
  336. {
  337. IntPtr ptrWnd = IntPtr.Zero;
  338. uint uiPid = (uint)Process.GetCurrentProcess().Id; // 当前进程 ID
  339. object objWnd = processWnd[uiPid];
  340. if (objWnd != null)
  341. {
  342. ptrWnd = (IntPtr)objWnd;
  343. if (ptrWnd != IntPtr.Zero && IsWindow(ptrWnd)) // 从缓存中获取句柄
  344. {
  345. return ptrWnd;
  346. }
  347. else
  348. {
  349. ptrWnd = IntPtr.Zero;
  350. }
  351. }
  352. bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);
  353. // 枚举窗口返回 false 并且没有错误号时表明获取成功
  354. if (!bResult && Marshal.GetLastWin32Error() == 0)
  355. {
  356. objWnd = processWnd[uiPid];
  357. if (objWnd != null)
  358. {
  359. ptrWnd = (IntPtr)objWnd;
  360. }
  361. }
  362. return ptrWnd;
  363. }
  364. private static bool EnumWindowsProc(IntPtr hwnd, uint lParam)
  365. {
  366. uint uiPid = 0;
  367. if (GetParent(hwnd) == IntPtr.Zero)
  368. {
  369. GetWindowThreadProcessId(hwnd, ref uiPid);
  370. if (uiPid == lParam) // 找到进程对应的主窗口句柄
  371. {
  372. processWnd[uiPid] = hwnd; // 把句柄缓存起来
  373. SetLastError(0); // 设置无错误
  374. return false; // 返回 false 以终止枚举窗口
  375. }
  376. }
  377. return true;
  378. }
  379. public static IntPtr GetCurrentWindowHandle(uint proid)
  380. {
  381. IntPtr ptrWnd = IntPtr.Zero;
  382. uint uiPid = proid;
  383. object objWnd = processWnd[uiPid];
  384. if (objWnd != null)
  385. {
  386. ptrWnd = (IntPtr)objWnd;
  387. if (ptrWnd != IntPtr.Zero && IsWindow(ptrWnd)) // 从缓存中获取句柄
  388. {
  389. return ptrWnd;
  390. }
  391. else
  392. {
  393. ptrWnd = IntPtr.Zero;
  394. }
  395. }
  396. bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);
  397. // 枚举窗口返回 false 并且没有错误号时表明获取成功
  398. if (!bResult && Marshal.GetLastWin32Error() == 0)
  399. {
  400. objWnd = processWnd[uiPid];
  401. if (objWnd != null)
  402. {
  403. ptrWnd = (IntPtr)objWnd;
  404. }
  405. }
  406. return ptrWnd;
  407. }
  408. }
  409. }