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

    Question

  • 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[i] != 0)
           {
             processID=aProcesses[i];

             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;
    }

    Friday, December 7, 2018 2:04 AM

All replies