Question

Getting the file path by using a window handle.

Asked by: PoeticAudio

Hey guys,

I was just wondering if there was a way to get the full file path by using a window handle.  For example if the user selects the Notepad window then it will show "C:\Documents and Settings\SSynan\Start Menu\Programs\Accessories\Notepad.exe" (or whatever window). I tried messing with TLHelp32 but the best I could get is the file name, not the full path.

I know how to do all the necessary code to locate the window, I just don't know how to get the file path. Btw, this will be used on both WindowsXP and Windows 2000.

Best Regards,
- Steven

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-04-26 at 08:29:20ID20967815
Topic

Delphi Programming

Participating Experts
4
Points
250
Comments
21

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Kill Application with process id e.g notepad.exe
    How can i kill application like notepad not with findwindow, i will search for the processID like notepad.exe and send WM_CLOSE or WM_DESTROY. Can i check notepad is running and the kill the application? Can you write complete code, i'm not so good in this Regards Trausti
  2. Notepad.exe
    When i try to open a txt file with Notepad, it came out an error message "The NOTEPAD.EXE file is linked to missing export SHELL32.W98:SHGetSpecialFolderPathA." twice.. then another window "D:\ac.txt , A device attached to the system is not functioning." ....
  3. How to programmatically end process (notepad.exe) in …
    Hi To ALL, This little tool scans CD-DVD and close Apps as soon as user press eject button on drive. Problem with this code is that doesnt recognise Player as Window title because new song is new title. "WPPlay" works fine. What I would like to do is instead Find...
  4. Call an connection on WindowsXP
    How I can call a internet connection in WindowsXP? In Windows98 I can use the RAS, but how I can execute a connection created in WindowsXP? Thanks for All.
  5. How does notepad.exe work?
    I use notepad.exe to open a .txt file and use Winpooch to monitor the file::open,file::wirte,Reg::SetValue,Reg::QueryValue,Sys::Execute,Sys::KillProcess all operations. The first time I open a .txt file, winpooch ask me wether accept this operation.When the next time I open ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: shaneholmesPosted on 2004-04-26 at 08:42:05ID: 10919499

You can use GetModuleFileName to retrieve the name of an EXE from a
module handle. However,  using GetModuleFilename only works on Win32 if the window
is part of your own process.

You need to use Toolhelp32 functions (on Win95
only) or PSAPI.DLL (NT 4) to get from a process ID (which you obtain from the
window handle via GetWindowthreadProcessID) to the filename of the EXE.

Delphi
encapsulates Toolhelp32 in the TlHelp32 unit.


procedure GetExePath(WH : HWND; var Exepath : string);
var
  dwActiveProcessId : DWORD;
  Snap   : THandle;
  pe32   : TPROCESSENTRY32;
Begin
  GetWindowThreadProcessId(WH, @dwActiveProcessId );
  try
    Snap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,
dwActiveProcessId);
    if Snap <> 0 then
    begin
      if Process32First(Snap, pe32) then
      begin
        if pe32.th32ProcessID = dwActiveProcessId then
        begin
          ExePath := String(pe32.szExeFile);
        end
        else
        begin
          while Process32Next(Snap, pe32) do
          begin
            if pe32.th32ProcessID = dwActiveProcessId then
            begin
              ExePath := String(pe32.szExeFile);
              Break;
            end; //of: if pe32.th32ProcessID = dwActiveProcessId
          end; //of while
        end; //of else
      end; //of: if Process32First(Snap, pe32)
    end; //of: if Snap <> 0
  finally
    CloseHandle(Snap);
  end;
end;


Shane

 

by: shaneholmesPosted on 2004-04-26 at 08:45:12ID: 10919530

Or  as a function:

Shane


function GetExePath(WH : HWND): String;
var
  dwActiveProcessId : DWORD;
  Snap   : THandle;
  pe32   : TPROCESSENTRY32;
Begin
 result:= '';
  GetWindowThreadProcessId(WH, @dwActiveProcessId );
  try
    Snap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,
dwActiveProcessId);
    if Snap <> 0 then
    begin
      if Process32First(Snap, pe32) then
      begin
        if pe32.th32ProcessID = dwActiveProcessId then
        begin
          result := String(pe32.szExeFile);
        end
        else
        begin
          while Process32Next(Snap, pe32) do
          begin
            if pe32.th32ProcessID = dwActiveProcessId then
            begin
              Result := String(pe32.szExeFile);
              Break;
            end; //of: if pe32.th32ProcessID = dwActiveProcessId
          end; //of while
        end; //of else
      end; //of: if Process32First(Snap, pe32)
    end; //of: if Snap <> 0
  finally
    CloseHandle(Snap);
  end;
end;

 

by: MadshiPosted on 2004-04-26 at 09:00:05ID: 10919726

The toolhelp functions can be used everywhere except NT4. The problem is that while the toolhelp functions do return the full file path in win9x, they only return the file NAME in the winNT family. So if you need the full path in the NT family you need to use PsApi.dll. This works in the whole winNT family, but not in win9x.

 

by: shaneholmesPosted on 2004-04-26 at 09:06:33ID: 10919784

Soory, your right, i was typing so fast, i got my self reversed, however, the code does use the psAPI.dll

SMILE

SHane

 

by: MadshiPosted on 2004-04-26 at 09:12:37ID: 10919871

Which code uses the pasApi.dll? Your code uses toolhelp32. Now I'm confused...   :-)

 

by: shaneholmesPosted on 2004-04-26 at 09:23:01ID: 10919983

Yeah, im confusing my self as well.

It is quite complicated, in fact. as quoted from (Peter Below (TeamB))

"Win16:

  use GetWindowWord( hwnd, GWW_INSTANCE ) to get the module handle, with that
  GetModuleFilename gets the exe name. ExtractIcon can be used to fetch an
  icon from the EXE.
 
Win95/98, NT 5.0:
  use GetWindowThreadProcessID to get the process ID from the window handle.
  Use Toolhelp32 to enumerate all running processes and look for one with a
  matching process ID. The process info contains the exe name. Get icon with
  ExtractIconEx or ShGetFileInfo. Delphi comes with an import unit for
  Toolhelp32 (tlhelp32).

NT 4.0:
  use GetWindowThreadProcessID to get the process ID from the window handle.
  Use PSAPI.DLL to enumerate all running processes and look for one with a
  matching process ID. The process info contains the exe name. Get icon with
  ExtractIconEx or ShGetFileInfo. A import unit for PSAPI.DLL can be
  downloaded from www.xapware.com or http://www.wilsonc.demon.co.uk."


Shane

 

by: MadshiPosted on 2004-04-26 at 09:28:40ID: 10920044

But as I said before, the toolhelp functions do NOT give us the full file path when being used in the NT family. And the question is about getting the full file path in the NT family. So that means toolhelp is no go.

You need to use PsApi.dll. That works in NT4, Windows 2000, Windows XP and Windows 2003 - but not in win9x.

 

by: PoeticAudioPosted on 2004-04-26 at 09:31:48ID: 10920074

So how would I use psAPI.dll to achieve this?

 

by: shaneholmesPosted on 2004-04-26 at 09:32:26ID: 10920083

Win95/98, NT 5.0:
  use GetWindowThreadProcessID to get the process ID from the window handle.
  Use Toolhelp32 to enumerate all running processes and look for one with a
  matching process ID. The process info contains the exe name. Get icon with
  ExtractIconEx or ShGetFileInfo. Delphi comes with an import unit for
  Toolhelp32 (tlhelp32).

SHane

 

by: shaneholmesPosted on 2004-04-26 at 09:33:47ID: 10920101

OK Madshi, im listening...... cause i think im confused., hopefully you can set me straight as well....

code please....

Shane

 

by: MadshiPosted on 2004-04-26 at 09:57:35ID: 10920350

Shane, in Windows 2000, XP and Windows 2003 you can use *both* the toolhelp functions and PsApi.dll. Normally everyone uses the toolhelp functions, that's why Peter Below suggested that. However, in the NT family the toolhelp functions only return the file name of the running processes, NOT the full path. So in order to get the full path you need to use PsApi.dll.

Sorry to say, but I don't have any PsApi.dll code ready to go.

As Shane quoted:

"A import unit for PSAPI.DLL can be downloaded from www.xapware.com or http://www.wilsonc.demon.co.uk."

Alternatively you could also use my madKernel packages, which is free for non-commercial usage (only). But I think it might be a bit overkill, if all you want to do is process enumeration. Anyway, just for the sake of completeness here's the madKernel documentation:

http://help.madshi.net/madKernel.htm

With it you could do this:

uses madKernel;

begin
  ShowMessage( Window(someWindowHandle).OwnerProcess.ExeFile );

That would return the full path in all 32bit Windows operating systems. But the madKernel package is quite big, so perhaps you're better of by using psapi directly.

 

by: shaneholmesPosted on 2004-04-26 at 09:59:10ID: 10920373

THANKS Madshi!

Shane

 

by: PoeticAudioPosted on 2004-04-26 at 10:20:45ID: 10920574

I was hoping to keep the program as small as possible, besides I will be using this program at work, so that solution looks like a no-go...hmm this is harder then it should be...

 

by: MadshiPosted on 2004-04-26 at 10:24:03ID: 10920608

Just do a search on google. I'm sure that I've seen some Delphi psapi.dll sources somewhen somewhere. Look for "Delphi psapi".

 

by: shaneholmesPosted on 2004-04-26 at 10:39:43ID: 10920741

Yup, and when I did, i found this great source of yours....

In win9x the code also gives you the full path, but
not in win2k and winXP. In those systems you need
to use psApi.dll to get the full path:

http://www.howtodothings.com/showarticle.asp?article=142

Shane

 

by: DaFoxPosted on 2004-04-28 at 03:16:09ID: 10937268

Hi,

just to (hopefully) complete the above comments:

function GetExenameForProcessUsingPSAPI(pid: DWord): String;
var
  i: Integer;
  cbNeeded: DWord;
  modules: array [1..1024] of hInst;
  ProcHandle: THandle;
  filename: array [0..512] of Char;
begin
  SetLastError(0);
  result := '';
  ProcHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, pid);
  if (ProcHandle <> 0) then
  try
    if (EnumProcessModules(ProcHandle, @modules[1], SizeOf(modules), cbNeeded)) then
      for i := 1 to cbNeeded div SizeOf(hInst) do
      begin
        if (GetModuleFilenameEx(ProcHandle, modules[i], filename, SizeOf(filename)) > 0) then
          if (AnsiStrIComp(PChar(ExtractFileExt(filename) + #0), '.exe' ) = 0) then
          begin
            Result := filename;
            break;
          end;
      end;
  finally
    CloseHandle(ProcHandle);
  end;
end;

function GetExenameForProcessUsingToolhelp32(pid: DWord): String;
var
  snapshot: THandle;
  procentry: TProcessEntry32;
  ret: bool;
begin
  SetLastError(0);
  Result := '';
  snapshot:= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if (snapshot <> INVALID_HANDLE_VALUE) then
  try
    procentry.dwSize := Sizeof(procentry);
    ret := Process32FIRST(snapshot, procentry);
    while ret do
    begin
      if (procentry.th32ProcessID = pid) then
      begin
        Result := procentry.szExeFile;
        break;
      end else
        ret := Process32Next(snapshot, procentry);
    end;
  finally
    CloseHandle(snapshot);
  end;
End;

function GetExenameForProcess(pid: DWord): String;
begin
  if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion <= 5)
  then
    Result := GetExenameForProcessUsingPSAPI(pid)
  else
    Result := GetExenameForProcessUsingToolhelp32(pid);
end;

function GetExenameForWindow(wnd: hWnd): String;
var
  pid: DWord;
begin
  Result := '';
  if isWindow(Wnd) then
  begin
    GetWindowThreadProcessID(Wnd, @pid);
    if (pid <> 0) then Result := GetExenameForProcess(pid);
  end;
end;

Regards,
Markus

 

by: Ivanov_GPosted on 2004-05-15 at 12:01:46ID: 11077432

The GetModuleFileName function retrieves the full path and filename for the executable file containing the specified module.

DWORD GetModuleFileName(
    HMODULE hModule,      // handle to module to find filename for
    LPTSTR lpFilename,      // pointer to buffer for module path
    DWORD nSize       // size of buffer, in characters
   );      
 

Parameters:
   hModule - Identifies the module whose executable filename is being requested. If this parameter is NULL, GetModuleFileName returns the path for the file used to create the calling process.
   lpFilename - Points to a buffer that is filled in with the path and filename of the given module.
   nSize - Specifies the length, in characters, of the lpFilename buffer. If the length of the path and filename exceeds this limit, the string is truncated.

Return Values
If the function succeeds, the return value is the length, in characters, of the string copied to the buffer.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

 

by: Ivanov_GPosted on 2004-05-23 at 02:10:17ID: 11136714

procedure TForm1.Button1Click(Sender: TObject);
var
  Buff : array[0..255] of char;
  size : Integer;
  str  : String;
  i, j : Integer;
begin
  size := sizeof(Buff);
  j := GetModuleFileName(hInstance, Buff, size);
  str := '';
  for i := 0 to j do
    str := str + Buff[i];
  ShowMessage(str);
end;

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...