Check if process is running in Delphi IDE

Post date: Mar 16, 2010 2:58:22 PM

Overview:

  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.
    1. 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.
Uses
   tlhelp32
var
   lclCurrProc: TProcessEntry32;
   lclPrntProc: TProcessEntry32;
   lclSnapHndl: THandle;
   lclEXEName: String;
   lclPrntName: String;
begin
    // 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);
    repeat
      if lclCurrProc.szExeFile = lclEXEName then
        Break;
    until (not Process32Next(lclSnapHndl, lclCurrProc));
    // find parent process
    Process32First(lclSnapHndl, lclPrntProc);
    repeat
      if lclPrntProc.th32ProcessID = lclCurrProc.th32ParentProcessID then
        Break;
    until (not Process32Next(lclSnapHndl, lclPrntProc));
    lclPrntName := lclPrntProc.szExeFile;
        if AnsiCompareText(lclPrntName, 'Delphi32.exe') = 0 then
      ShowMessage('Inside Delphi')
    else
      ShowMessage('NOT Inside Delphi');
end;