1,效果以嵌入Modbus Slave为例:
2,代码:
public partial class Form1 : Form{//设置嵌入exe的常量private const int nIndex = -16;private const int dwNewLong = 0x10000000;Process m_AppProcess;public Form1(){InitializeComponent();btnApp.Enabled = false;}private void btnAppFilePath_Click(object sender, EventArgs e){using (OpenFileDialog ofd = new OpenFileDialog()){ofd.Filter = "可执行文件*.exe|*.exe";ofd.Multiselect = false;ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);if (ofd.ShowDialog() == DialogResult.OK){lblExeFilePath.Text = ofd.FileName;btnApp.Enabled = true;}}}private void btnApp_Click(object sender, EventArgs e){if (lblExeFilePath.Text.Trim().Length == 0){MessageBox.Show("请先选择需要执行的exe文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);return;}int num = panel1.Controls.Count;ProcessStartInfo info = new ProcessStartInfo();info.FileName = lblExeFilePath.Text.Trim();info.UseShellExecute = false;info.CreateNoWindow = false;info.WindowStyle = ProcessWindowStyle.Minimized;m_AppProcess = Process.Start(info);if (m_AppProcess.WaitForInputIdle(-1)){System.Threading.Thread.Sleep(500);if (EmbedProcess( panel1)){return;}}MessageBox.Show("启动失败!");}/// <summary>/// 将指定路径的Exe文件嵌入到指定的窗口容器中/// </summary>/// <param name="processPath">进程路径</param>/// <param name="sleepTime">等待启动时间,单位ms</param>/// <param name="parentControl">父容器</param>/// <returns></returns>bool EmbedProcess( Control parentControl){//等待应用启动// EmbedProcess(path, 1000, panel1);// System.Threading.Thread.Sleep(sleepTime);// Environment.Is64BitOperatingSystem//获取该进程的句柄try{SetParent(m_AppProcess.MainWindowHandle, parentControl.Handle);//去除边框//判断系统位数if (IntPtr.Size == 4){//32位系统SetWindowLongPtr32(new HandleRef(this, m_AppProcess.MainWindowHandle), nIndex, dwNewLong);}else{//64位系统SetWindowLongPtr64(new HandleRef(this, m_AppProcess.MainWindowHandle), nIndex, dwNewLong);}//移动窗体MoveWindow(m_AppProcess.MainWindowHandle, 0, 0, parentControl.Width, parentControl.Height, true);}catch (Exception){return false;}return true;}//将子窗体嵌入到父窗体,可用于在窗体中嵌入Exe文件[DllImport("user32.dll", SetLastError = true)]static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);//32位系统使用,作用去除边框[DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, int dwNewLong);//64位系统使用,作用去除边框[DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)]static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, int dwNewLong);//移动窗体[DllImport("user32.dll", SetLastError = true)]static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);}