How to check if a win32 exe file is already running? (use win32 API code)

Viewed 974

I want to check if a win32 EXE file is already running (only knowing the file path and name).

Please tell me how to realize it with win32 API code.

Thanks a lot!

I mean to have each EXE path only running one instance.

3 Answers

By reading Remy Lebeau's answer I succeed to check if the current application is already running in other processes with the following code:

DWORD processes[4096];
DWORD bytesGot;
EnumProcesses(processes, sizeof processes, &bytesGot);
DWORD processesCount = bytesGot / sizeof(DWORD);

WCHAR currName[MAX_PATH];
GetModuleFileNameEx(GetCurrentProcess(), NULL, currName, MAX_PATH);
DWORD currProcessId = GetCurrentProcessId();

for(int x=0;x<=processesCount-1;x++)
{
    HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processes[x]);
    WCHAR name[MAX_PATH];
    GetModuleFileNameEx(process,NULL, name, MAX_PATH);
    CloseHandle(process);
    if (processes[x]!=currProcessId&& wcscmp(name, currName)==0) return 0;
}

Thanks to Remy Lebeau a lot :) Great useful hints.

create a blank file on startup and check the file exist.

Related