获取当前进程(程序)主窗体句柄并设置wpf的父窗体为此句柄

2021-04-20 08:25

阅读:343

标签:window   ntp   import   logs   程序   html   charset   阅读   解决   

原文:获取当前进程(程序)主窗体句柄并设置wpf的父窗体为此句柄

有时候在c++调用wpf控件的时候,wpf控件想自己显示窗体,但需要设置owner属性。迂回解决办法是设置wpf的window窗体的父窗体为进程的句柄。

 

1.获取当前进程id

 int id = Process.GetCurrentProcess().Id;

 

2.根据进程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;
            }
        }

 3.设置wpf的window的父窗体为当前进程主窗口句柄,完整代码如下:

  int id = Process.GetCurrentProcess().Id;
            IntPtr mainPtr = ProcessHelper.GetProcessHandle(id);
            var win = new Window();
            new WindowInteropHelper(win) { Owner = mainPtr }; 
            win.Show();

 

 

 感谢阅读。

获取当前进程(程序)主窗体句柄并设置wpf的父窗体为此句柄

标签:window   ntp   import   logs   程序   html   charset   阅读   解决   

原文地址:https://www.cnblogs.com/lonelyxmas/p/8628312.html


评论


亲,登录后才可以留言!