c# - 检测新应用并在面板中运行

标签 c# .net winforms detection

我正在创建在面板内运行另一个应用程序的应用程序。

[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);
    }
}

enter image description here

关于c# - 检测新应用并在面板中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51112490/

相关文章:

c# - 使用 StreamReader.EndOfStream 的问题?

c# - .net 的免费内存分析器

C# WinForms : How to set Main function STAThreadAttribute

c# - 将相同的方法值传递给多个表单

c# - 哪个更好?数组、ArrayList 或 List<T>(在性能和速度方面)

c# - 用于打开枚举以选择 namespace /类的反射替代方案

c# - 如何在 Dapper.Net 中编写一对多查询?

asp.net - 如何使用 Active Directory 创建具有个人用户帐户的新 .NET 应用程序?

c# - 向按钮添加 UAC 屏蔽并保留其背景图像?

c# - Open XML - 如何向 docx 文档添加水印