
应朋友要求,需要将一个第三方应用程序嵌入到本程序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(); while (true)
{
P = FindWindow(null, title);//通过标题查找窗口句柄,当然也可以按class查找,如果需要查找子窗口需要FindWindowEx函数
Thread.Sleep();
if (P == IntPtr.Zero)
continue;
else
break;
}
try
{
// 将外部应用程序嵌入到本窗口
long ret = SetParent(P, this.panel1.Handle);
if (ret == )
{
MessageBox.Show("ErrorCode:"+ GetLastError().ToString());
} // 移除边框样式
SetWindowLong(new HandleRef(this, P), GWL_STYLE, WS_VISIBLE); //移动窗口
MoveWindow(P, , , this.Width, this.Height, true);
}
catch (Exception ex1)
{
Console.WriteLine(ex1.Message);
} }
主要参考来源:
http://blog.csdn.net/llddyy123wq/article/details/5624625