欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

从进程中操作WPF窗体的显示隐藏

程序员文章站 2022-07-13 22:33:07
...

一、问题描述

如何在一个进程中,打开另一个进程中的wpf已经隐藏的窗体

二、解决方案

1、在WPF进程中,获取该窗体的句柄,并保存到某个文件,这个文件可以是内存映射文件,也可以是普通的xml文件。在WPF的MainWindow中,添加

     private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            IntPtr hwnd = new WindowInteropHelper(MainWnd).Handle;//窗体句柄
            WriteHandleToXML(hwnd.ToString());
        }

        private void WriteHandleToXML(string input)
        {
            XElement xmlTree1 = new XElement("Root",  new XElement("Child", input));

            string strFile = System.Environment.CurrentDirectory + @"\MyFile.xml";
            xmlTree1.Save(strFile);

        }

2、重点,在window_Closing事件与OnActivated事件中,

 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Hide();
            e.Cancel = true;
        }

       protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            Show();
        }

3、在另一个进程中,读取XML文件,获取句柄,显示窗体


        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

      private const int SW_HIDE = 0;              //常量,隐藏
        private const int SW_SHOWNORMAL = 1;        //常量,显示,标准状态
        private const int SW_SHOWMINIMIZED = 2;     //常量,显示,最小化
        private const int SW_SHOWMAXIMIZED = 3;     //常量,显示,最大化
        private const int SW_SHOWNOACTIVATE = 4;    //常量,显示,不**
        private const int SW_RESTORE = 9;           //常量,显示,回复原状
        private const int SW_SHOWDEFAULT = 10;      //常量,显示,默认

private void ShowWPFWindow()
{ 
string handle = "";
string strFile = System.Environment.CurrentDirectory + @"\MyFile.xml";

                XmlDocument xmlDoc = new XmlDocument();

                xmlDoc.Load(strFile);


                XmlNode xn = xmlDoc.SelectSingleNode("Root");

                XmlNodeList xnl = xn.ChildNodes;
                XmlElement xe = (XmlElement)xnl[0];
                handle = xe.InnerText;
                int nHand = Int32.Parse(handle);// 获得文件中的句柄(字符串类型)// 转整型
                IntPtr intPtr = (IntPtr)nHand;// 转句柄
               
              bool b = ShowWindowAsync(intPtr, SW_SHOWNORMAL); //显示该句柄的窗口,如果没有显示则返回false
}

参考:

https://cloud.tencent.com/developer/ask/217950

https://blog.csdn.net/wmqdn/article/details/8961248

https://blog.csdn.net/b510030/article/details/52526270

https://blog.csdn.net/dxcgis/article/details/5757187?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-5&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-5

相关标签: C#