简体   繁体   English

如何在C#中获取启动的App的PID

[英]How to get PID of started App in C#

I have got a few pairs of the identical apps. 我有几对相同的应用程序。

It looks like 看起来像

Pair 1: App A + App B 配对1:App A + App B

Pair 2: App A + App B 配对2:App A + App B

and etc 等等

Each App A starts App B from its folder. 每个应用程序A都从其文件夹启动应用程序B。 (They are both at the same folder.) (它们都在同一文件夹中。)

So I start it like this 所以我这样开始

Code of App A 应用程式A的程式码

Process p = new Process();
p.StartInfo.FileName = FileManager.AppDirectoryName + "\\" + AppB;
p.Start();

And I also stop App B like this. 而且我也这样停止了AppB。

foreach (Process p in Process.GetProcesses())
{  
    if (p.ProcessName == AppB)
    {
        p.Kill();
        return;
    }
} 

The problem is that at the same time could be many App B executing so this method does not allow to detect target App B to kill. 问题在于,同时可能有许多App B正在执行,因此此方法不允许检测到目标App B被杀死。

I assume to use PID of App B to kill it. 我假设使用App B的PID杀死它。 But I don't know how to obtain PID at the moment to start App B... 但是我不知道如何在启动App B时获取PID ...

Any clue? 有什么线索吗?

启动应用程序后,Process对象上的Id属性将指示新启动的进程的PID

var PID = p.Id;

Save a reference to the Process object: 保存对Process对象的引用:

Process p = new Process();
p.StartInfo.FileName = @"c:\windows\notepad.exe";
p.Start();

// ...

p.Kill();

or remember its PID: 或记住其PID:

Process p = new Process();
p.StartInfo.FileName = @"c:\windows\notepad.exe";
p.Start();

long pid = p.Id;

// ...

Process.GetProcessById(pid).Kill();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM