bool haveMainWindow = false;
IntPtr mainWindowHandle = IntPtr.Zero;
int processId = 0;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
processId = Process.GetCurrentProcess().Id;
///获取句柄
IntPtr hwnd = GetMainWindowHandle(processId);
}
private IntPtr GetMainWindowHandle(int processId)
{
if (!haveMainWindow)
{
this.mainWindowHandle = IntPtr.Zero;
this.processId = processId;
User32API.EnumThreadWindowsCallback callback = new User32API.EnumThreadWindowsCallback(this.EnumWindowsCallback);
User32API.EnumWindows(callback, IntPtr.Zero);
GC.KeepAlive(callback);
haveMainWindow = true;
}
return this.mainWindowHandle;
}
private bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter)
{
int num;
User32API.GetWindowThreadProcessId(new HandleRef(this, handle), out num);
if ((num == this.processId) && this.IsMainWindow(handle))
{
this.mainWindowHandle = handle;
return false;
}
return true;
}
private bool IsMainWindow(IntPtr handle)
{
return (!(User32API.GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero) && User32API.IsWindowVisible(new HandleRef(this, handle)));
}
c# 获取程序句柄
最新推荐文章于 2022-11-22 19:17:02 发布