在Win10下调用Process.MainWindowHandle会提示应用程序已退出

时间:2022-01-19 08:56:37

应伴侣要求,需要将一个第三方应用措施嵌入到本措施WinForm窗口,以前在VB6时代做过类似的成果,其道理就是操作Windows API中FindWindow函数找到第三方应用措施句柄,再操作SetParent函数,将该句柄设置为本窗口的子窗口。

网上搜索大部分都是操作System.Diagnostics.Process获取外部应用措施的MainWindowHandle,貌似以前的COM应用措施可以,在Win10下挪用Process.MainWindowHandle会提示“应用措施已退出”,也就是获取不到应用措施句柄。于是转换思路,操作FindWindow查找窗口句柄,测试告成。

但是需要注意的是,有些第三方应用措施对访谒权限要求高,需要“以打点员身份运行"/bin/debug"下的exe文件才华告成嵌入,代码调试无效,调试模式挪用SetParent会返回-5错误。

以下是部分代码:

/// <summary> /// 将指定的措施嵌入指定的控件 /// </summary> private void EmbedProcess() { string title = System.Configuration.ConfigurationManager.AppSettings["Title"];//要查找的外部应用措施窗口标题 IntPtr P = new IntPtr(0); while (true) { P = FindWindow(null, title);//通过标题查找窗口句柄,固然也可以按class查找,如果需要查找子窗口需要FindWindowEx函数 Thread.Sleep(100); if (P == IntPtr.Zero) continue; else break; } try { // 将外部应用措施嵌入到本窗口 long ret = SetParent(P, this.panel1.Handle); if (ret == 0) { MessageBox.Show("ErrorCode:"+ GetLastError().ToString()); } // 移除边框样式 SetWindowLong(new HandleRef(this, P), GWL_STYLE, WS_VISIBLE); //移动窗口 MoveWindow(P, 0, 0, this.Width, this.Height, true); } catch (Exception ex1) { Console.WriteLine(ex1.Message); } }

点击这里下载源码