如何获取Windows / C#顶层窗口的进程名称和标题

前端之家收集整理的这篇文章主要介绍了如何获取Windows / C#顶层窗口的进程名称和标题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
主题…或更好的 – 如何从顶部窗口更改事件时获取这些信息?
感谢提示.所以我应该使用P / Invoke.这是完整的代码
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.InteropServices;
  5.  
  6. namespace CuckooCoach
  7. {
  8. class Monitor
  9. {
  10. [DllImport("user32.dll")]
  11. private static extern IntPtr GetForegroundWindow();
  12.  
  13. [DllImport("user32.dll")]
  14. static extern int GetWindowTextLength(IntPtr hWnd);
  15.  
  16. // int GetWindowText(
  17. // __in HWND hWnd,// __out LPTSTR lpString,// __in int nMaxCount
  18. // );
  19. [DllImport("user32.dll")]
  20. private static extern int GetWindowText(IntPtr hWnd,StringBuilder lpString,int nMaxCount);
  21.  
  22. // DWORD GetWindowThreadProcessId(
  23. // __in HWND hWnd,// __out LPDWORD lpdwProcessId
  24. // );
  25. [DllImport("user32.dll")]
  26. private static extern uint GetWindowThreadProcessId(IntPtr hWnd,out uint lpdwProcessId);
  27.  
  28. //HANDLE WINAPI OpenProcess(
  29. // __in DWORD dwDesiredAccess,// __in BOOL bInheritHandle,// __in DWORD dwProcessId
  30. //);
  31. [DllImport("kernel32.dll")]
  32. private static extern IntPtr OpenProcess(uint dwDesiredAccess,bool bInheritHandle,uint dwProcessId);
  33.  
  34. [DllImport("kernel32.dll")]
  35. private static extern bool CloseHandle(IntPtr handle);
  36.  
  37. // DWORD WINAPI GetModuleBaseName(
  38. // __in HANDLE hProcess,// __in_opt HMODULE hModule,// __out LPTSTR lpBaseName,// __in DWORD nSize
  39. // );
  40. [DllImport("psapi.dll")]
  41. private static extern uint GetModuleBaseName(IntPtr hWnd,IntPtr hModule,StringBuilder lpFileName,int nSize);
  42.  
  43. // DWORD WINAPI GetModuleFileNameEx(
  44. // __in HANDLE hProcess,// __out LPTSTR lpFilename,// __in DWORD nSize
  45. // );
  46. [DllImport("psapi.dll")]
  47. private static extern uint GetModuleFileNameEx(IntPtr hWnd,int nSize);
  48.  
  49. public static string GetTopWindowText()
  50. {
  51. IntPtr hWnd = GetForegroundWindow();
  52. int length = GetWindowTextLength(hWnd);
  53. StringBuilder text = new StringBuilder(length + 1);
  54. GetWindowText(hWnd,text,text.Capacity);
  55. return text.ToString();
  56. }
  57.  
  58. public static string GetTopWindowName()
  59. {
  60. IntPtr hWnd = GetForegroundWindow();
  61. uint lpdwProcessId;
  62. GetWindowThreadProcessId(hWnd,out lpdwProcessId);
  63.  
  64. IntPtr hProcess = OpenProcess(0x0410,false,lpdwProcessId);
  65.  
  66. StringBuilder text = new StringBuilder(1000);
  67. //GetModuleBaseName(hProcess,IntPtr.Zero,text.Capacity);
  68. GetModuleFileNameEx(hProcess,text.Capacity);
  69.  
  70. CloseHandle(hProcess);
  71.  
  72. return text.ToString();
  73. }
  74.  
  75. }
  76. }

猜你在找的Windows相关文章