我正在创建在面板内运行另一个应用程序的应用程序。
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
public Form3() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
Process p = Process.Start(@"path\app.exe");
Thread.Sleep(200); // Allow the process to open it's window
SetParent(p.MainWindowHandle, panel1.Handle);
}
但问题是,app.exe 有时(我知道什么时候)创建新窗口作为新应用程序。我想将这个新窗口添加到新面板中。
private Process GetProcess() {
//do some magic stuff and find actually running app
return NewAppProcess;
}
private void button2_Click(object sender, EventArgs e) {
Process p = GetProcess();
SetParent(p.MainWindowHandle, panel2.Handle);
}
感谢所有能把我推向正确道路的一切
最佳答案
使用 ManagementEventWatcher
, 你可以看Win32_ProcessStartTrace
在新进程启动时接收事件。
示例
在这个例子中,我展示了如何观看 mspaint.exe
的启动并将其添加为表单中的 Panel
的子项。为此,将对 System.Management
dll 的引用添加到您的项目中,然后使用以下代码。
注意 1:观察者的速度不是很快,您可能会看到窗口在桌面上打开,然后位于面板中。
注解 2:这是一个示例,使用 mspaint.exe
显示很热门。如果您在真正的 app.exe
上应用该解决方案时遇到任何问题,您需要专门询问您的 app.exe
的解决方案。
注意 3:确保以管理员身份运行。
using System.Management;
using System.Runtime.InteropServices;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
ManagementEventWatcher watcher;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
watcher = new ManagementEventWatcher(
"Select * From Win32_ProcessStartTrace Where ProcessName = 'mspaint.exe'");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
var id = (UInt32)e.NewEvent["ProcessID"];
var process = System.Diagnostics.Process.GetProcessById((int)id);
this.Invoke(new MethodInvoker(() => {
SetParent(process.MainWindowHandle, panel1.Handle);
}));
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
watcher.Stop();
watcher.Dispose();
base.OnFormClosed(e);
}
}
关于c# - 检测新应用并在面板中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51112490/