通过调用API 方法实现嵌入第三方程序窗口到指定容器
Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;namespace winformEmbedingExample
{public partial class Form1 : Form{[DllImport("user32.dll", SetLastError = true)]private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);[DllImport("user32.dll", SetLastError = true)]private static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);[DllImport("user32.dll", EntryPoint = "GetWindowLong")]private static extern int GetWindowLong(IntPtr hWnd, int nIndex);[DllImport("user32.dll", EntryPoint = "SetWindowLong")]private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);private const int GWL_STYLE = -16;private const int WS_CAPTION = 0xC00000;private Process process;private const int WS_CHILD = 0x40000000;private const int WS_VISIBLE = 0x10000000;public Form1(){InitializeComponent();Load += Form1_Load;Closing += Form1_Closing;}private void Form1_Closing(object sender, CancelEventArgs e){Process[] ps = Process.GetProcessesByName("Project2");foreach (var p in ps) {p.Kill();}}private void Form1_Load(object sender, EventArgs e){}private void StartThirdPartApplication(){process = Process.Start("Project2.exe");process.WaitForInputIdle();IntPtr pWnd = process.MainWindowHandle;int style = GetWindowLong(pWnd, GWL_STYLE);style &= ~WS_CAPTION;style |= WS_CHILD;SetWindowLong(pWnd, GWL_STYLE, style);SetParent(pWnd, panel1.Handle);MoveWindow(pWnd, 0, 0, panel1.Width, panel1.Height, false);}private void button2_Click(object sender, EventArgs e){StartThirdPartApplication();}}
}
效果