关注另一个应用程序,如果它关闭关闭我的应用程序(不投票)C#应用程序、我的

2023-09-07 15:24:10 作者:花落相思尽

喜    我想钩子的另一个应用程序,以便它关闭时,我可以关闭我的申请。

hi I want to "hook" another application so when it closes I can close my application.

我不想轮询正在运行的进程,因为这似乎是不必要的密集,如果我想在实时响应。

I don't want to poll the running process as this seems unnecessarily intensive, if I want to respond in real-time.

我相信应用程序发送消息窗口中创建或关闭等我怎么能勾这知道它关闭时?当他们

I believe apps send out message within windows when they are created or closed etc how can I hook this to know when it closes?

例如,假设我正在运行的进程,以确保记事本应用程序加载检查装载,如果是它保持加载到记事本被关闭。如记事本被关闭我的应用程序有些是如何知道这一点,并退出...

for example lets say my app loads checks running processes to ensure notepad is loaded and if so it remains loaded until notepad is closed. as notepad is closed my app some how knows this and exits...

这是可能的如果又如何?

is this possible if so how?

它需要工作在XP Vista和WIN7

it needs to work on xp vista and win7

推荐答案

如果您对运行的应用程序,你可以使用Process.WaitForExit将阻塞,直到进程被关闭的流程实例。当然,你可以把WaitForExit在另一个线程,这样你的主线程不会阻塞。

If you have the Process instance for the running application you can use Process.WaitForExit which will block until the process is closed. Of course you can put the WaitForExit in another thread so that your main thread does not block.

下面是一个例子,不使用一个单独的线程

Here is an example, not using a separate thread

Process[] processes = Process.GetProcessesByName("notepad");
if (processes.Length > 0)
{
  processes[0].WaitForExit();
}

下面是一个使用一个线程来监控流程的简单版本。

Here is a simple version using a thread to monitor the process.

public static class ProcessMonitor
{
  public static event EventHandler ProcessClosed;

  public static void MonitorForExit(Process process)
  {
    Thread thread = new Thread(() =>
    {
      process.WaitForExit();
      OnProcessClosed(EventArgs.Empty);
    });
    thread.Start();      
  }

  private static void OnProcessClosed(EventArgs e)
  {
    if (ProcessClosed != null)
    {
      ProcessClosed(null, e);
    }
  }
}

下面控制台code是如何在上述可以使用的一个例子。该会工作同样出色的当然是WPF或WinForms应用程序,但要记住,对UI你不能直接从事件回调,因为它从UI线程独立的线程中运行更新UI。有很多的例子在计算器说明如何从一个非UI线程更新用户界面的WinForms和WPF这里。

The following Console code is an example of how the above can be used. This would work equally well in a WPF or WinForms app of course, BUT remember that for UI you cannot update the UI directly from the event callback because it it run in a separate thread from the UI thread. There are plenty of examples here on stackoverflow explaining how to update UI for WinForms and WPF from a non-UI thread.

static void Main(string[] args)
{
  // Wire up the event handler for the ProcessClosed event
  ProcessMonitor.ProcessClosed += new EventHandler((s,e) =>
  {
    Console.WriteLine("Process Closed");
  });

  Process[] processes = Process.GetProcessesByName("notepad");
  if (processes.Length > 0)
  {
    ProcessMonitor.MonitorForExit(processes[0]);
  }
  else
  {
    Console.WriteLine("Process not running");        
  }
  Console.ReadKey(true);
}