How can I catch another program running and in the case of its work, mine starts. If not, an error occurs. I now have this code

public Form1() { string pName = "steam.exe"; Process[] pList = Process.GetProcesses(); foreach (Process myProcess in pList) { if (myProcess.ProcessName == pName) { InitializeComponent(); } else{ MessageBox.Show("Steam не запущен!!!!"); Environment.Exit(0); } } } 

When the program starts, an error occurs. Fulfills the else branch. Although I myself have launched Steam.

  • At your first process with a different name, the end of the program happens. - Monk
  • @Monk And how do I get out of this situation? - Petr
  • one
    Leave only the if branch, and remove the else branch. - Monk
  • @Monk earned. But now if the same Steam is not running, then I just have an empty form. - Petr

1 answer 1

The first way: we enter a boolean flag variable.

 string pName = "steam.exe"; Process[] pList = Process.GetProcesses(); bool found = false; foreach (var myProcess in pList) { if (myProcess.ProcessName == pName) { InitializeComponent(); found = true; break; } } if (!found) { MessageBox.Show("Steam не запущен!"); Environment.Exit(0); } 

The second way: we do an additional method.

Recommended way.

 bool FindProcess() { string pName = "steam.exe"; Process[] pList = Process.GetProcesses(); foreach (var myProcess in pList) { if (myProcess.ProcessName == pName) { return true; } } return false; } 

We use it:

 if (FindProcess()) { InitializeComponent(); } else { MessageBox.Show("Steam не запущен!"); Environment.Exit(0); } 

Third way: use goto

("Ay, it hurts! Just not on the head! Don't kick ...")

Not recommended way.

 string pName = "steam.exe"; Process[] pList = Process.GetProcesses(); foreach (var myProcess in pList) { if (myProcess.ProcessName == pName) { goto FOUND; } } MessageBox.Show("Steam не запущен!"); Environment.Exit(0); FOUND: InitializeComponent(); 

In general, it is better to remove this code from the form designer to the Program.cs file, to the Main method. If the required application is running, only then call the string Application.Run(new Form1()); - your form opens. Otherwise, there is no point in even calling the form.

  • Wow. Thanks for the detailed answer :) - Petr