C# 在进程启动时关闭 window

C# Close window when process is started

我有一个 WPF window,它应该在“TeamViewer”进程启动时关闭。

不幸的是,我无法构建合适的循环。你能帮帮我吗?

 private void Window_Loaded(object sender, RoutedEventArgs e)
    {


       Process[] pname = Process.GetProcessesByName("TeamViewer");
       do
        {
            this.Close();
        }
       while (pname.Length > 0);

    }

问候 斯蒂芬

您应该在循环中查找进程“TeamViewer”,找到它的任何实例后,您就可以退出表单。 示例代码,这个是watches for Notepad实例,大家可以根据自己的需要修改。

     do
     {
         Process[] proc = Process.GetProcessesByName("notepad");
         if (null != proc)
         {
              if (proc.Length > 0)
              {
                   //if any notepad process is running, then exit
                    return;
              }
         }

         //wait for some time, there are other efficient wait mechanisms
         Thread.Sleep(500); //wait for half sec

     }while(true);