zoukankan      html  css  js  c++  java
  • C# 获取指定进程的主窗口句柄

    静态方法,直接上代码吧:

     1 using System;
     2 using System.Runtime.InteropServices;
     3 
     4 namespace Macroresolute
     5 {
     6     public static class ProcessEx
     7     {
     8         private static class NativeMethods
     9         {
    10             internal const uint GW_OWNER = 4;
    11 
    12             internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
    13 
    14             [DllImport("User32.dll", CharSet = CharSet.Auto)]
    15             internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
    16 
    17             [DllImport("User32.dll", CharSet = CharSet.Auto)]
    18             internal static extern int GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId);
    19 
    20             [DllImport("User32.dll", CharSet = CharSet.Auto)]
    21             internal static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
    22 
    23             [DllImport("User32.dll", CharSet = CharSet.Auto)]
    24             internal static extern bool IsWindowVisible(IntPtr hWnd);
    25         }
    26 
    27         public static IntPtr GetMainWindowHandle(int processId)
    28         {
    29             IntPtr MainWindowHandle = IntPtr.Zero;
    30 
    31             NativeMethods.EnumWindows(new NativeMethods.EnumWindowsProc((hWnd, lParam) =>
    32             {
    33                 IntPtr PID;
    34                 NativeMethods.GetWindowThreadProcessId(hWnd, out PID);
    35 
    36                 if (PID == lParam &&
    37                     NativeMethods.IsWindowVisible(hWnd) &&
    38                     NativeMethods.GetWindow(hWnd, NativeMethods.GW_OWNER) == IntPtr.Zero)
    39                 {
    40                     MainWindowHandle = hWnd;
    41                     return false;
    42                 }
    43 
    44                 return true;
    45 
    46             }), new IntPtr(processId));
    47 
    48             return MainWindowHandle;
    49         }
    50     }
    51 }
    52
    作者:周耀帅
    本文版权归作者和博客园共有,欢迎转载。但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    利用服务器实现疫情查询小系统(Web版+APP)
    第五周总结
    第四周总结
    初试python爬取网页数据
    使用ECharts完成数据可视化
    第三周总结
    第二周总结
    求数组中最大子数组的和
    软工第二周博客作业
    MySQL学习笔记(3)——创建、查看、修改、删除数据库
  • 原文地址:https://www.cnblogs.com/zys529/p/2470039.html
Copyright © 2011-2022 走看看