如何在WPF中实现软件内嵌效果

发布于:2025-02-12 ⋅ 阅读:(53) ⋅ 点赞:(0)

1.创建Process进程,设置运行程序文件路径

Process proc = new Process();
proc.StartInfo.FileName = @"C:\Users\hdevelop.exe";
proc.Start();
proc.WaitForInputIdle();

2.根据创建的进程获取窗口句柄

IntPtr hWnd = proc.MainWindowHandle;

3.开启线程,当获取的句柄不为空过的时候,将获取到的窗口与自己创建的窗体进行绑定

if (hWnd != IntPtr.Zero)
{

    SetWindow.intPtr = hWnd;
    //这里是WPF的写法,Winform把this.Dispatcher.Invoke改为this.Invoke即可
    this.Dispatcher.Invoke(new Action(() =>
    {
        SetWindow.SetParent(tempPanel.Handle, "TempWindow", this);  //设置父容器
    }));
}
else
{
    System.Windows.MessageBox.Show("未能查找到窗体");
}

嵌入容器的方法以及需要调用的API为:

/// <summary>
/// 将第三方窗体嵌入到容器内
/// </summary>
/// <param name="hWndNewParent">父容器句柄</param>
/// <param name="windowName">窗体名</param>
public static void SetParent(IntPtr hWndNewParent, string windowName, MainWindow window)
{

    ShowWindow(intPtr, 0);                 //先将窗体隐藏,防止出现闪烁
    SetParent(intPtr, hWndNewParent);      //将第三方窗体嵌入父容器                    
    Thread.Sleep(100);                      //略加延时
    ShowWindow(intPtr, 3);                 //让第三方窗体在容器中最大化显示
    RemoveWindowTitle(intPtr);// 去除窗体标题
}


#region API 需要using System.Runtime.InteropServices;

[DllImport("user32.dll ", EntryPoint = "SetParent")]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);   //将外部窗体嵌入程序

[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpszClass, string lpszWindow);      //按照窗体类名或窗体标题查找窗体

[DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);                  //设置窗体属性

[DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, long dwNewLong);

[DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)]
public static extern long GetWindowLong(IntPtr hWnd, int nIndex);

#endregion

/// <summary>
/// 去除窗体标题
/// </summary>
/// <param name="vHandle">窗口句柄</param>
public static void RemoveWindowTitle(IntPtr vHandle)
{
    long style = GetWindowLong(vHandle, -16);
    style &= ~0x00C00000;
    SetWindowLong(vHandle, -16, style);
}

以上就已经将外部窗体嵌入至现有窗体,如果需要调整内嵌尺寸则可以调用方法

 /// <summary>
 /// 调整第三方应用窗体大小,intPtr为获取到的程序窗口句柄
 /// </summary>
 public static void ResizeWindow()
 {
     ShowWindow(intPtr, 0);  //先将窗口隐藏
     ShowWindow(intPtr, 3);  //再将窗口最大化,可以让第三方窗口自适应容器的大小
 }