您的位置:首页 > 编程语言 > C#

C# 获取指定进程的主窗口句柄

2012-04-25 16:26 549 查看
静态方法,直接上代码吧:

using System;
using System.Runtime.InteropServices;

namespace Macroresolute
{
public static class ProcessEx
{
private static class NativeMethods
{
internal const uint GW_OWNER = 4;

internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

[DllImport("User32.dll", CharSet = CharSet.Auto)]
internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

[DllImport("User32.dll", CharSet = CharSet.Auto)]
internal static extern int GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId);

[DllImport("User32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

[DllImport("User32.dll", CharSet = CharSet.Auto)]
internal static extern bool IsWindowVisible(IntPtr hWnd);
}

public static IntPtr GetMainWindowHandle(int processId)
{
IntPtr MainWindowHandle = IntPtr.Zero;

NativeMethods.EnumWindows(new NativeMethods.EnumWindowsProc((hWnd, lParam) =>
{
IntPtr PID;
NativeMethods.GetWindowThreadProcessId(hWnd, out PID);

if (PID == lParam &&
NativeMethods.IsWindowVisible(hWnd) &&
NativeMethods.GetWindow(hWnd, NativeMethods.GW_OWNER) == IntPtr.Zero)
{
MainWindowHandle = hWnd;
return false;
}

return true;

}), new IntPtr(processId));

return MainWindowHandle;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: