知道窗口句柄,怎么得到该程序的文件名???

解决方案 »

  1.   

    先通过GetWindowThreadProcessId取得窗口所属进程的PID,再通过枚举系统进程,得到该进程的文件名。枚举进程可以通过系统快照:CreateToolhelp32Snapshot, Process32First, Process32Next等API来进行。
      

  2.   

    uses tlhelp32;function CrnGetExeFileFromWindow(hWin: HWND): string;
    var
        dwPID: DWORD;
        strExePath: String;
        pToolhelp: THandle;
        pe: TProcessEntry32;
        me: TModuleEntry32;
        bOK: bool;
    begin
        GetWindowThreadProcessId(hWin, @dwPID);
        // 建立系统快照
        pToolhelp := CreateToolhelp32Snapshot(TH32CS_SNAPALL, dwPID);
        // 获取可执行文件的路径
        if Win32Platform <> VER_PLATFORM_WIN32_NT then // Win9x
        begin
            ZeroMemory(@pe, SizeOf(pe));
            pe.dwSize := SizeOf(pe);
            bOK := Process32First(pToolhelp, pe);
            while(bOK) do
            begin
                if pe.th32ProcessID = dwPID then
                begin
                    strExePath := pe.szExeFile;
                    break;
                end;
                bOK := Process32Next(pToolhelp, pe);
            end;
        end
        else // WinNT
        begin
            ZeroMemory(@me, SizeOf(me));
            me.dwSize := SizeOf(me);
            Module32First(pToolhelp, me);
            strExePath := me.szExePath;
        end;
        CloseHandle(pToolhelp);
        Result := strExePath;
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
        hWin: THandle;
    begin
        // 这里替换成你要查询的窗口句柄就可以了,我随便指定了一个值。
        hWin := THandle($008C0302); 
        ShowMessage(CrnGetExeFileFromWindow(hWin));
    end;