using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetClassName(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount);
static void Main()
{
// 创建一个窗体
Form form = new Form();
form.Text = "Panel Example";
form.Size = new System.Drawing.Size(500, 500);
// 创建一个 Panel 控件
Panel panel = new Panel();
panel.Dock = DockStyle.Fill;
// 添加 Panel 到窗体中
form.Controls.Add(panel);
// 启动第三方程序,并将其嵌入到 Panel 控件中
string thirdPartyExePath = "YourThirdPartyProgram.exe"; // 第三方程序的路径
IntPtr panelHandle = panel.Handle;
IntPtr thirdPartyHandle = StartThirdPartyProgram(thirdPartyExePath, panelHandle);
// 获取 Panel 控件中嵌入的第三方程序的句柄
IntPtr embeddedHandle = GetEmbeddedHandle(panelHandle);
if (embeddedHandle != IntPtr.Zero)
{
Console.WriteLine("Third Party Program Handle: " + embeddedHandle.ToString());
}
else
{
Console.WriteLine("Third Party Program not found in Panel.");
}
// 显示窗体
Application.Run(form);
}
static IntPtr StartThirdPartyProgram(string exePath, IntPtr parentHandle)
{
// 启动第三方程序,并将其窗体嵌入到指定的父窗体中
// 这里需要你根据第三方程序的启动方式进行适当的调整
// 这个示例只是简单地打开一个新的进程
ProcessStartInfo startInfo = new ProcessStartInfo(exePath);
Process thirdPartyProcess = Process.Start(startInfo);
IntPtr thirdPartyHandle = thirdPartyProcess.MainWindowHandle;
SetParent(thirdPartyHandle, parentHandle); // 设置父窗体为 Panel 控件
return thirdPartyHandle;
}
static IntPtr GetEmbeddedHandle(IntPtr parentHandle)
{
IntPtr embeddedHandle = IntPtr.Zero;
IntPtr childHandle = IntPtr.Zero;
// 遍历 Panel 控件的子控件,查找第三方程序的句柄
do
{
childHandle = FindWindowEx(parentHandle, childHandle, null, null);
if (childHandle != IntPtr.Zero)
{
// 这里可以根据需要添加更多的判断条件,以确定找到的是第三方程序的窗体
embeddedHandle = childHandle;
break;
}
} while (childHandle != IntPtr.Zero);
return embeddedHandle;
}
}
06-06