WinApi.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 GetWindowsHandle(string WindowName)
  55. {
  56. IntPtr hwnd = IntPtr.Zero;
  57. Process[] procs = Process.GetProcessesByName(WindowName);
  58. if (procs.Length != 0)
  59. {
  60. hwnd = procs[0].MainWindowHandle;
  61. //MessageBox.Show("??" + procs[0].Id.ToString() + "??" + procs[0].MainWindowHandle.ToString());
  62. //Global.writeLog("GetWindowsHandle=>ProcessID:" + procs[0].Id + ",ManagedThreadId:" + Thread.CurrentThread.ManagedThreadId.ToString());
  63. //Global.writeLog("GetWindowsHandle=>CurrentProcessID:" + Process.GetCurrentProcess().Id);
  64. }
  65. //Process ps = procs[0];
  66. //Global.writeLog("Start");
  67. //for (int i = 0; i < ps.Threads.Count; i++)
  68. //{
  69. // var thread = ps.Threads[i];
  70. // string str = string.Empty;
  71. // str = str + "标识符(" + i.ToString() + "):"+ thread.Id.ToString() + System.Environment.NewLine;
  72. // //str = str + "标识符:" + thread. + System.Environment.NewLine;
  73. // str = str +"基本优先级:" + thread.BasePriority.ToString() + System.Environment.NewLine;
  74. // str = str +"当前优先级:" + thread.CurrentPriority.ToString() + System.Environment.NewLine;
  75. // str = str +"内存地址:" + thread.StartAddress.ToInt32() + System.Environment.NewLine;
  76. // str = str +"启动时间:" + thread.StartTime.ToString() + System.Environment.NewLine;
  77. // str = str +"使用时间:" + thread.UserProcessorTime.ToString() + System.Environment.NewLine;
  78. // str = str + "当前状态:";
  79. // switch (thread.ThreadState)
  80. // {
  81. // case System.Diagnostics.ThreadState.Initialized:
  82. // str = str +"线程已经初始化但尚未启动";
  83. // break;
  84. // case System.Diagnostics.ThreadState.Ready:
  85. // str = str +"线程准备在下一个可用的处理器上运行";
  86. // break;
  87. // case System.Diagnostics.ThreadState.Running:
  88. // str = str +"当前正在使用处理器";
  89. // break;
  90. // case System.Diagnostics.ThreadState.Standby:
  91. // str = str +"线程将要使用处理器";
  92. // break;
  93. // case System.Diagnostics.ThreadState.Terminated:
  94. // str = str +"线程已完成执行并退出";
  95. // break;
  96. // case System.Diagnostics.ThreadState.Transition:
  97. // str = str +"线程在可以执行钱等待处理器之外的资源";
  98. // break;
  99. // case System.Diagnostics.ThreadState.Unknown:
  100. // str = str +"状态未知";
  101. // break;
  102. // case System.Diagnostics.ThreadState.Wait:
  103. // str = str +"正在等待外围操作完成或者资源释放";
  104. // break;
  105. // default:
  106. // break;
  107. // }
  108. // if (thread.ThreadState == System.Diagnostics.ThreadState.Wait)
  109. // {
  110. // str = str + System.Environment.NewLine +"等待原因:";
  111. // switch (thread.WaitReason)
  112. // {
  113. // case ThreadWaitReason.EventPairHigh:
  114. // str = str +"线程正在等待事件对高";
  115. // break;
  116. // case ThreadWaitReason.EventPairLow:
  117. // str = str +"线程正在等待事件对低";
  118. // break;
  119. // case ThreadWaitReason.ExecutionDelay:
  120. // str = str +"线程执行延迟";
  121. // break;
  122. // case ThreadWaitReason.Executive:
  123. // str = str +"线程正在等待计划程序";
  124. // break;
  125. // case ThreadWaitReason.FreePage:
  126. // str = str +"线程正在等待可用的虚拟内存页";
  127. // break;
  128. // case ThreadWaitReason.LpcReceive:
  129. // str = str +"线程正在等待本地过程调用到达";
  130. // break;
  131. // case ThreadWaitReason.LpcReply:
  132. // str = str +"线程正在等待对本地过程调用的回复到达";
  133. // break;
  134. // case ThreadWaitReason.PageIn:
  135. // str = str +"线程正在等待虚拟内存页到达内存";
  136. // break;
  137. // case ThreadWaitReason.PageOut:
  138. // str = str +"线程正在等待虚拟内存页写入磁盘";
  139. // break;
  140. // case ThreadWaitReason.Suspended:
  141. // str = str +"线程执行暂停";
  142. // break;
  143. // case ThreadWaitReason.SystemAllocation:
  144. // str = str +"线程正在等待系统分配";
  145. // break;
  146. // case ThreadWaitReason.Unknown:
  147. // str = str +"线程因位置原因而等待";
  148. // break;
  149. // case ThreadWaitReason.UserRequest:
  150. // str = str +"线程正在等待用户请求";
  151. // break;
  152. // case ThreadWaitReason.VirtualMemory:
  153. // str = str +"线程正在等待系统分配虚拟内存";
  154. // break;
  155. // default:
  156. // break;
  157. // }
  158. // }
  159. // Global.writeLog("ThreadsInfo:" + procs[0].Id.ToString() + "_" + procs[0].ProcessName, "Count:" + ps.Threads.Count.ToString(), str);
  160. //}
  161. //Global.writeLog("End");
  162. //foreach (Process process in procs)
  163. //{
  164. // if (process.ProcessName.Contains(WindowName))
  165. // {
  166. // MessageBox.Show($"Process_Name = ({process.ProcessName}), Id = {process.Id}");
  167. // }
  168. //}
  169. //return GetCurrentWindowHandle((uint)procs[0].Id);
  170. //Process[] processes = Process.GetProcesses();
  171. //foreach (Process process in processes)
  172. //{
  173. // if (process.ProcessName.Contains(WindowName))
  174. // {
  175. // MessageBox.Show($"ProcessName = ({process.ProcessName}), Id = {process.Id}");
  176. // }
  177. //}
  178. return hwnd;
  179. }
  180. private static Hashtable processWnd = null;
  181. public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);
  182. //static User32API()
  183. //{
  184. // if (processWnd == null)
  185. // {
  186. // processWnd = new Hashtable();
  187. // }
  188. //}
  189. [DllImport("user32.dll", EntryPoint = "EnumWindows", SetLastError = true)]
  190. public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);
  191. [DllImport("user32.dll", EntryPoint = "GetParent", SetLastError = true)]
  192. public static extern IntPtr GetParent(IntPtr hWnd);
  193. [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
  194. public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);
  195. [DllImport("user32.dll", EntryPoint = "IsWindow")]
  196. public static extern bool IsWindow(IntPtr hWnd);
  197. [DllImport("kernel32.dll", EntryPoint = "SetLastError")]
  198. public static extern void SetLastError(uint dwErrCode);
  199. public static IntPtr GetCurrentWindowHandle()
  200. {
  201. IntPtr ptrWnd = IntPtr.Zero;
  202. uint uiPid = (uint)Process.GetCurrentProcess().Id; // 当前进程 ID
  203. object objWnd = processWnd[uiPid];
  204. if (objWnd != null)
  205. {
  206. ptrWnd = (IntPtr)objWnd;
  207. if (ptrWnd != IntPtr.Zero && IsWindow(ptrWnd)) // 从缓存中获取句柄
  208. {
  209. return ptrWnd;
  210. }
  211. else
  212. {
  213. ptrWnd = IntPtr.Zero;
  214. }
  215. }
  216. bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);
  217. // 枚举窗口返回 false 并且没有错误号时表明获取成功
  218. if (!bResult && Marshal.GetLastWin32Error() == 0)
  219. {
  220. objWnd = processWnd[uiPid];
  221. if (objWnd != null)
  222. {
  223. ptrWnd = (IntPtr)objWnd;
  224. }
  225. }
  226. return ptrWnd;
  227. }
  228. private static bool EnumWindowsProc(IntPtr hwnd, uint lParam)
  229. {
  230. uint uiPid = 0;
  231. if (GetParent(hwnd) == IntPtr.Zero)
  232. {
  233. GetWindowThreadProcessId(hwnd, ref uiPid);
  234. if (uiPid == lParam) // 找到进程对应的主窗口句柄
  235. {
  236. processWnd[uiPid] = hwnd; // 把句柄缓存起来
  237. SetLastError(0); // 设置无错误
  238. return false; // 返回 false 以终止枚举窗口
  239. }
  240. }
  241. return true;
  242. }
  243. public static IntPtr GetCurrentWindowHandle(uint proid)
  244. {
  245. IntPtr ptrWnd = IntPtr.Zero;
  246. uint uiPid = proid;
  247. object objWnd = processWnd[uiPid];
  248. if (objWnd != null)
  249. {
  250. ptrWnd = (IntPtr)objWnd;
  251. if (ptrWnd != IntPtr.Zero && IsWindow(ptrWnd)) // 从缓存中获取句柄
  252. {
  253. return ptrWnd;
  254. }
  255. else
  256. {
  257. ptrWnd = IntPtr.Zero;
  258. }
  259. }
  260. bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), uiPid);
  261. // 枚举窗口返回 false 并且没有错误号时表明获取成功
  262. if (!bResult && Marshal.GetLastWin32Error() == 0)
  263. {
  264. objWnd = processWnd[uiPid];
  265. if (objWnd != null)
  266. {
  267. ptrWnd = (IntPtr)objWnd;
  268. }
  269. }
  270. return ptrWnd;
  271. }
  272. }
  273. }