Check if process is running in Delphi IDE

posted 16 Mar 2010, 07:58 by Delphi Basics
  1. Use the "CreateToolHelp32SnapShot" API to get a snap shot of all current running processes. 
  2. Cycle through the snap shot (using the Process32First and Process32Next API functions) looking for your executable. These function calls return a structure containing good information about the process. 
  3. After you find the structure for your executable. It will contain the Id for the parent process. 
  4. Cycle through the snap shot again (using the same Process32First and Process32Next functions, as before) and look for the process who's Id matches the parent Id from the structure found in #2). When you find the parent process you then look at the name of the parent process (in the structure that gets returned) If it is "delphi32.exe", then you're running in the Delphi debugger. If it is "explorer.exe" (or something else) then you are not. 

   lclCurrProc: TProcessEntry32;
   lclPrntProc: TProcessEntry32;
   lclSnapHndl: THandle;
   lclEXEName: String;
   lclPrntName: String;

    // Grab the snap shot of the current Process List
    lclSnapHndl := CreateToolHelp32SnapShot(TH32CS_SNAPALL, 0);

    // Save the name of your executable
    lclEXEName := ExtractFileName(Application.ExeName);

    // you must define the size of these structures.
    lclCurrProc.dwSize := SizeOf(TProcessEntry32);
    lclPrntProc.dwSize := SizeOf(TProcessEntry32);

    // find current process
    Process32First(lclSnapHndl, lclCurrProc);
      if lclCurrProc.szExeFile = lclEXEName then
    until (not Process32Next(lclSnapHndl, lclCurrProc));

    // find parent process
    Process32First(lclSnapHndl, lclPrntProc);
      if lclPrntProc.th32ProcessID = lclCurrProc.th32ParentProcessID then
    until (not Process32Next(lclSnapHndl, lclPrntProc));

    lclPrntName := lclPrntProc.szExeFile;

        if AnsiCompareText(lclPrntName, 'Delphi32.exe') = 0 then
      ShowMessage('Inside Delphi')
      ShowMessage('NOT Inside Delphi');