我希望C#程序可以在其他程序运行时启动。例如当我运行photoshop我的程序自行运行时或当我关闭photo shop我的程序关闭时
答案 0 :(得分:0)
您不能直接在简单的应用程序中执行此操作,需要创建一个Service来列出所有过程,并在创建特定过程时采取措施。 服务的主体可能如下所示:
using System.Diagnostics;
Process yourProcess;
bool triggerRunning;
public void OnUpdate()
{
bool triggerStillRunning = false;
//list all processes
var processes = Process.GetProcesses();
foreach(var p in processes)
{
//if trigger process is running
if (p.ProcessName == /*Photoshop*/)
{
//set variable indicating that it is still running
triggerStillRunning = true;
//if the process was not running last update
if(!triggerRunning)
{
//start your application
yourProcess = Process.Start(/*your app*/);
//set variable indicating that the trigger is still running
triggerRunning = true;
}
}
}
//check if the trigger was running last update but isnt running this update
if (!triggerStillRunning && triggerRunning)
{
//kill all instances of your application
foreach (var process in Process.GetProcessesByName("whatever"))
{
process.Kill();
}
}
}
请注意,您仍然需要将此逻辑包装在服务中。最好看一下我链接过的教程,该服务的原因必须在单独的项目和可执行文件中。