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.