Monday, June 11, 2012

GET THE PATH AND FILENAME OF THE FOREGROUND WINDOW APPLICATION


uses
   ..., psapi;

function GetForegroundApp: String;
var  hwndFG:        HWND;
     hProc:         THandle;
     hMod:          Array [0..0] of HMODULE;
     dwPID:         DWORD;
     dwSize:        DWORD;
     dwCount:       DWORD;
begin

  // Set default result
  SetLength(result, 0);

  // Get the foreground window
  hwndFG:=GetForegroundWindow;

  // Check handle
  if (hwndFG <> 0) then
  begin
     // Get process id for the window handle
     if (GetWindowThreadProcessID(hwndFG, @dwPID) <> 0) then
     begin
        // Convert process id to a process handle
        hProc:=OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, True, dwPID);
        // Check handle
        if (hProc <> 0) then
        begin
           // Resource protection
           try
              // Set count
              dwCount:=0;
              // Get the first module, which is the exe
              if EnumProcessModules(hProc, @hMod, SizeOf(HMODULE), dwCount) then
              begin
                 // Allocate memory for file name
                 SetLength(result, Succ(MAX_PATH));
                 // Attempt to get the module file name
                 dwSize:=GetModuleFileNameEx(hProc, hMod[0], Pointer(result), MAX_PATH);
                 // Reset string length
                 SetLength(result, dwSize);
              end;
           finally
              // Close handle
              CloseHandle(hProc);
           end;
        end;
     end;
  end;
end;

0 comments:

Post a Comment

 
Related Posts Plugin for WordPress, Blogger...