How can I keep the program from being opened when it's already running

  • Thread starter Thread starter TallGuy63
  • Start date Start date
T

TallGuy63

Guest
I get issues occasionally with my programs running while another copy of the exe is running in the background.

I tried putting in a check when the program opens but it doesn't always catch the other copy that's running



LONG findprogram()
{
LONG count;
DWORD aProcesses[1024],cbNeeded,cProcesses,processID,CurrentProcessId,lpExitCode;
unsigned int i;
TCHAR szProcessName[MAX_PATH]=TEXT("<unknown>");
HANDLE hProcess;
HMODULE hMod;
std::string namepath="programname.exe";
std::string cmpnamepath;
std::wstring wtxt;

CurrentProcessId=GetCurrentProcessId();

if(!EnumProcesses(aProcesses,sizeof(aProcesses),&cbNeeded))
{
return 0;
}

cProcesses=cbNeeded/sizeof(DWORD);
count=1; //number of processes running

for(i=0;i<cProcesses;i++)
{
if(aProcesses != 0)
{
processID=aProcesses;

if(processID == CurrentProcessId) //leave out current program
continue;

// Get a handle to the process.
hProcess=OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,processID);

// Get the process name.

if(hProcess != NULL)
{
if(EnumProcessModules(hProcess,&hMod,sizeof(hMod),&cbNeeded))
{
GetModuleBaseName(hProcess,hMod,szProcessName,sizeof(szProcessName)/sizeof(TCHAR));
}
}

wtxt=szProcessName;
cmpnamepath=wstrtostr(wtxt);

if(ucase(cmpnamepath) == ucase(namepath))
{
count++;
GetExitCodeProcess(hProcess,&lpExitCode);
TerminateProcess(hProcess,lpExitCode);
}

CloseHandle(hProcess);
}
}

return count;
}

Continue reading...
 
Back
Top