获取当前进程(程序)主窗体句柄并设置wpf的父窗体为此句柄
2021-05-02 21:28
标签:import imp private dllimport visible 控件 log return proc 有时候在c++调用wpf控件的时候,wpf控件想自己显示窗体,但需要设置owner属性。迂回解决办法是设置wpf的window窗体的父窗体为进程的句柄。 1.获取当前进程id 2.根据进程id获取进程主句柄 3.设置wpf的window的父窗体为当前进程主窗口句柄,完整代码如下: 感谢阅读。 获取当前进程(程序)主窗体句柄并设置wpf的父窗体为此句柄 标签:import imp private dllimport visible 控件 log return proc 原文地址:http://www.cnblogs.com/lizhijian/p/7755617.html int id = Process.GetCurrentProcess().Id;
public static class ProcessHelper
{
private static class Win32
{
internal const uint GwOwner = 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 GetProcessHandle(int processId)
{
IntPtr processPtr = IntPtr.Zero;
Win32.EnumWindows((hWnd, lParam) =>
{
IntPtr pid;
Win32.GetWindowThreadProcessId(hWnd, out pid);
if (pid == lParam &&
Win32.IsWindowVisible(hWnd) &&
Win32.GetWindow(hWnd, Win32.GwOwner) == IntPtr.Zero)
{
processPtr = hWnd;
return false;
}
return true;
}, new IntPtr(processId));
return processPtr;
}
}
int id = Process.GetCurrentProcess().Id;
IntPtr mainPtr = ProcessHelper.GetProcessHandle(id);
var win = new Window();
new WindowInteropHelper(win) { Owner = mainPtr };
win.Show();
文章标题:获取当前进程(程序)主窗体句柄并设置wpf的父窗体为此句柄
文章链接:http://soscw.com/index.php/essay/81506.html