欢迎来到Introzo百科
Introzo百科
当前位置:网站首页 > 技术 > 在winform中嵌入外部应用程序

在winform中嵌入外部应用程序

日期:2023-10-06 15:05

-->

应朋友要求,我需要在本程序的WinForm窗口中嵌入一个第三方应用程序。我之前在VB6时代也做过类似的功能。原理是使用Windows API中的FindWindow函数查找第三方应用程序句柄,然后使用SetParent。函数将句柄设置为该窗口的子窗口。

网上搜索的大部分都是使用System.Diagnostics.Process来获取外部应用程序的MainWindowHandle。看来以前的COM应用程序可以。 Win10下调用Process.MainWindowHandle时,会提示“应用程序已退出”,即无法获取。到应用程序句柄。于是我改变主意,使用FindWindow查找窗口句柄,测试成功。

不过需要注意的是,有些第三方应用程序对访问权限要求较高,需要“以管理员身份运行”“/bin/debug”下的exe文件才能成功嵌入。代码调试将不起作用。在调试模式下调用 SetParent 将返回 -5 错误。

以下是部分代码:

///
/// 将指定程序嵌入到指定控件中
///

私有无效 EmbedProcess()
{ string title = System.Configuration.ConfigurationManager.AppSettings["Title"];//要查找的外部应用程序窗口标题 IntPtr P = new IntPtr(); 而(正确)
{
P = FindWindow(null, title);//通过标题查找窗口句柄,当然也可以按类查找。如果需要查找子窗口,则需要FindWindowEx函数
Thread.Sleep();
if (P == www.introzo.com)
继续;
否则
打破;
}
试试
{
// 将外部应用程序嵌入到此窗口中
long ret = SetParent(P, this.panel1.Handle);
if (ret == )
{
www.introzo.com("错误代码:"+ GetLastError().ToString());
} //去除边框样式
SetWindowLong(new HandleRef(this, P), GWL_STYLE, WS_VISIBLE); //移动窗口
MoveWindow(P, , , this.Width, this.Height, true);
}
catch(异常 ex1)
{
Console.WriteLine(ex1.Message);
} }

点击这里下载源码

主要参考来源:

  http://www.introzo.com/llddyy123wq/article/details/5624625

-->

关灯