0

I had been searching through the internet for getting all the processes of an application. And so far all the implementation of traversing it is by using foreach loop which I'm not familiar with. It works but I just can't rest easy for it working without me getting to understand it. So I'd like to ask if someone can show me how to implement such code using for loop.

System::Diagnostics::Process^ current = System::Diagnostics::Process::GetCurrentProcess();
for each (System::Diagnostics::Process^ process in System::Diagnostics::Process::GetProcessesByName(current->ProcessName))
    if (process->Id != current->Id)
    {
        // process already exist
    }


I'm using visual studio c++/clr btw, hence :: since it's not in c#.

1 Answers1

0

GetProcessesByName returns a cli::array, so iterate using that and its length property.

cli::array<Process^>^ processes = Process::GetProcessesByName(current->ProcessName);
for (int i = 0; i < processes->Length; i++)
{
    if (processes[i]->Id != current->Id)
    {
        // process already exist
    }
}

That said, there might be a better way to do this.

It looks like you're trying to see if there's another copy of your application running, so that you can display an "App is already running, switch to that one instead" message to the user.

The problem is that the process name here is just the filename of your EXE, without the path or the "EXE" extension. Try renaming your application to "Notepad.exe", and run a couple copies of the Windows Notepad, and you'll see that they both show up in the GetProcessesByName result.

A better way to do this is to create a named Mutex, and check for its existence and/or lock status at startup.

Here's an answer that does just that. Prevent multiple instances of a given app in .NET? It is written in C#, but it can be translated to C++/CLI. The only notable thing about the translation is that it's using a C# using statement; in C++/CLI that would be the line Mutex mutex(false, "whatever string");, using C++/CLI's stack semantics.

David Yaw
  • 27,383
  • 4
  • 60
  • 93