码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-10-30 19:50:36      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:import   imp   private   dllimport   visible   控件   log   return   proc   

有时候在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的父窗体为此句柄

标签:import   imp   private   dllimport   visible   控件   log   return   proc   

原文地址:http://www.cnblogs.com/lizhijian/p/7755617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!