什么是嵌入 EXE 程序
实现步骤
1. 创建 WinForms 项目
shell
dotnet new winforms -o EmbedExeApp
cd EmbedExeApp
2. 准备外部 EXE 程序
3. 使用 Windows API 嵌入 EXE
csharp
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class EmbedExeForm : Form
{
private const int GWL_STYLE = -16;
private const int WS_VISIBLE = 0x10000000;
[DllImport("user32.dll", EntryPoint = "SetParent")]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", EntryPoint = "ShowWindow")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
public EmbedExeForm()
{
// 设置窗体属性
this.Text = "EXE Embedding Demo";
this.Size = new System.Drawing.Size(800, 600);
}
private void EmbedExe(string exePath)
{
ProcessStartInfo startInfo = new ProcessStartInfo(exePath)
{
UseShellExecute = false,
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Normal
};
Process exeProcess = Process.Start(startInfo);
exeProcess.WaitForInputIdle();
IntPtr childHandle = exeProcess.MainWindowHandle;
SetParent(childHandle, this.Panel1.Handle);
ShowWindow(childHandle, 1);
MoveWindow(childHandle, 0, 0, this.Panel1.Width, this.Panel1.Height, true);
}
private void btnEmbedCalc_Click(object sender, EventArgs e)
{
EmbedExe("calc.exe");
}
}
4. 调用嵌入函数
csharp
private void btnEmbedCalc_Click(object sender, EventArgs e)
{
EmbedExe("calc.exe"); // 嵌入计算器程序
}
5. 运行并测试
注意事项
确保你有权限运行和嵌入目标 EXE 程序。
在调试和发布应用程序时,确保外部 EXE 文件的路径正确。
嵌入的 EXE 程序应该与主应用程序兼容,特别是在 DPI 和窗口尺寸方面。
结论
往期精品推荐: