Recent

Author Topic: How to get handle from the name of the exe file? (winapi)  (Read 11816 times)

superbzyku

  • Newbie
  • Posts: 2
How to get handle from the name of the exe file? (winapi)
« on: March 13, 2010, 12:43:42 pm »
Hi,
I try get a handle from the name of the exe file. but the application returns error when use this function:
Code: [Select]
unit get_hwnd_from_exename;
{$mode delphi}{$H+}
interface

uses
  Windows, SysUtils, jwatlhelp32;

function ExeProcessToHWnd(ProcessName : string) : HWND;

implementation

var
  PidNum : DWORD;
  AHandle : HWND;

function ExeProcessToHWnd(ProcessName : string) : HWND;
  function EnumProcess(hHwnd : HWND; lParam : integer) : boolean; stdcall;
  var
    pPid : DWORD;
  begin
    Result := (hHwnd <> 0);
    if Result = True then
    begin
      GetWindowThreadProcessId(hHwnd, pPid);
      if pPid = PidNum then
      begin
        if (GetWindowLong(hHWND, GWL_HWNDPARENT) = 0)
          and (IsWindowVisible(hHWND) or IsIconic(hHWND)) then
        begin
          AHandle := hHWND;
        end;
      end;
    end;
    Result := True;
  end;

  function ProcessIDFromAppname32(AppName : string) : DWORD;
  var
    SnapShot : THandle;
    processEntry : TProcessEntry32;
  begin
    Result := 0;
    AppName := AnsiUpperCase(AppName);
    SnapShot := CreateToolhelp32SnapShot(TH32CS_SNAPPROCESS, 0);
    if SnapShot <> 0 then
    try
      ProcessEntry.dwSize := SizeOf(ProcessEntry);
      if Process32First(SnapShot, ProcessEntry) then
        repeat
          if Pos(AppName, AnsiUpperCase(ExtractFilename
            (StrPas(processEntry.szExeFile)))) > 0 then
          begin
            Result := ProcessEntry.th32ProcessID;
            Break;
          end;
        until not Process32Next(SnapShot, ProcessEntry);
    finally
      CloseHandle(SnapShot);
    end;
  end;

begin
  PidNum := ProcessIDFromAppname32(ProcessName);
  EnumWindows(@EnumProcess, 0);
  Result := AHandle;
end;

end.

marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 12901
  • FPC developer.
Re: How to get handle from the name of the exe file? (winapi)
« Reply #1 on: March 13, 2010, 01:25:42 pm »

What returns which error where?

superbzyku

  • Newbie
  • Posts: 2
Re: How to get handle from the name of the exe file? (winapi)
« Reply #2 on: March 13, 2010, 01:36:16 pm »
" Project raised exception class 'External: SIGSEGV' "

when i want to run ExeProcessToHWnd

 

TinyPortal © 2005-2018