Print
View Comments

How do you find out if a process exists by its executable filename? Unfortunately there isn't a simple way to do this with Windows API. To accomplish this you will have to enumerate all of the processes using CreateToolhelp32Snapshot. You also may not see every process depending on what user you're running as. For most, this gets the job done. Feel free to use this and change it to fit your needs.

For this code you're going to need to include the header TlHelp32.h:

bool is_process(_In_ LPCTSTR exename, _Out_opt_ bool* failed)
{
	if(failed) *failed = false;
	
	// CHECK EXE NAME:
	if(exename == NULL || _tcslen(exename) < 1) {
		if(failed) *failed = true;
		return false;
	}
	
	// CREATE PROCESS SNAPSHOT:
	HANDLE snapshot_handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if(snapshot_handle == INVALID_HANDLE_VALUE) {
		if(failed) *failed = true;
		return false;
	}
	
	// SETUP MODULEENTRY STRUCT:
	PROCESSENTRY32 pe32 = {};
	pe32.dwSize = sizeof(PROCESSENTRY32);
	
	// FIRST PROCESS:
	if(!Process32FirstW(snapshot_handle, &pe32)) {
		CloseHandle(snapshot_handle);
		if(failed) *failed = true;
		return false;
	}
	
	// TRAVERSE PROCESSES:
	bool found = false;
	do {
		if(_tcsicmp(pe32.szExeFile, exename) == 0) {
			found = true;
			break;
		}
	} while(Process32NextW(snapshot_handle, &pe32));
	
	// CLEAN-UP:
	CloseHandle(snapshot_handle);
	
	return found;
}

 The second parameter is optional (pass NULL) and is only so you can determine if there was an actual error within the call.