什么是嵌入 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 partial class MainForm : 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 MainForm()
{
InitializeComponent();
}
private void EmbedProcess(string processPath)
{
ProcessStartInfo startInfo = new ProcessStartInfo(processPath)
{
UseShellExecute = false,
CreateNoWindow = true
};
Process process = Process.Start(startInfo);
IntPtr childHandle = process.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)
{
EmbedProcess("calc.exe");
}
}
4. 调用嵌入函数
csharp
private void btnEmbedCalc_Click(object sender, EventArgs e)
{
EmbedProcess("calc.exe"); // 嵌入计算器程序
}
5. 运行并测试
注意事项
确保在多线程环境下安全地访问 UI 控件。
在调试和发布应用程序时,确保外部 EXE 文件的路径正确。
嵌入的 EXE 程序应该与主应用程序兼容,特别是在 DPI 和窗口尺寸方面。
结论
往期精品推荐: