Windows find window handle

Handle v4.22

By Mark Russinovich

Published: June 14, 2019

Download Handle (887 KB)

Introduction

Ever wondered which program has a particular file or directory open? Now you can find out. Handle is a utility that displays information about open handles for any process in the system. You can use it to see the programs that have a file open, or to see the object types and names of all the handles of a program.

You can also get a GUI-based version of this program, Process Explorer, here at Sysinternals.

Installation

You run Handle by typing «handle». You must have administrative privilege to run Handle.

Usage

Handle is targeted at searching for open file references, so if you do not specify any command-line parameters it will list the values of all the handles in the system that refer to open files and the names of the files. It also takes several parameters that modify this behavior.

usage: handle [[-a] [-u] | [-c [-l] [-y]] | [-s]] [-p

Parameter Description
-a Dump information about all types of handles, not just those that refer to files. Other types include ports, Registry keys, synchronization primitives, threads, and processes.
-c Closes the specified handle (interpreted as a hexadecimal number). You must specify the process by its PID.
WARNING: Closing handles can cause application or system instability.
-l Dump the sizes of pagefile-backed sections.
-y Don’t prompt for close handle confirmation.
-s Print count of each type of handle open.
-u Show the owning user name when searching for handles.
-p Instead of examining all the handles in the system, this parameter narrows Handle’s scan to those processes that begin with the name process. Thus:
handle -p exp
would dump the open files for all processes that start with «exp», which would include Explorer.
name This parameter is present so that you can direct Handle to search for references to an object with a particular name.
For example, if you wanted to know which process (if any) has «c:\windows\system32» open you could type:
handle windows\system
The name match is case-insensitive and the fragment specified can be anywhere in the paths you are interested in.

Handle Output

When not in search mode (enabled by specifying a name fragment as a parameter), Handle divides its output into sections for each process it is printing handle information for. Dashed lines are used as a separator, immediately below which you will see the process name and its process id (PID). Beneath the process name are listed handle values (in hexadecimal), the type of object the handle is associated with, and the name of the object if it has one.

When in search mode, Handle prints the process names and id’s are listed on the left side and the names of the objects that had a match are on the right.

More Information

You can find more information on the Object Manager in Windows Internals, 4th Edition or by browsing the Object Manager name-space with WinObj.

Download Handle (887 KB)

FindWindowA function (winuser.h)

Retrieves a handle to the top-level window whose class name and window name match the specified strings. This function does not search child windows. This function does not perform a case-sensitive search.

To search child windows, beginning with a specified child window, use the FindWindowEx function.

Syntax

Parameters

The class name or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom must be in the low-order word of lpClassName; the high-order word must be zero.

If lpClassName points to a string, it specifies the window class name. The class name can be any name registered with RegisterClass or RegisterClassEx, or any of the predefined control-class names.

If lpClassName is NULL, it finds any window whose title matches the lpWindowName parameter.

The window name (the window’s title). If this parameter is NULL, all window names match.

Return value

If the function succeeds, the return value is a handle to the window that has the specified class name and window name.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

If the lpWindowName parameter is not NULL, FindWindow calls the GetWindowText function to retrieve the window name for comparison. For a description of a potential problem that can arise, see the Remarks for GetWindowText.

Examples

The winuser.h header defines FindWindow as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.

How to find window handle from exe file’s name

Imagine I have Firefox and I open Firefox Start Page, then I should have a Window with the title: «Mozilla Firefox Start Page — Mozilla Firefox».

I can find window handle with the code below

But what I want is find window handle from the window’s exe file’s name like this

Does windows Api has a function like FindWindowFromExe()? If it doesn’t, what is the best way to Find window from its exe?

Thanks for reading 🙂

1 Answer 1

There is no single API function to find a window by its owning process’s file name. You will have to search for it manually.

You can use EnumWindows() to enumerate all top-level windows, or use FindWindow() / FindWindowEx() to find/enumerate specific types of windows.

For each window, you can either:

  • use GetWindowThreadProcessId() to get the process ID that owns the window, then
  • use OpenProcess() to open a HANDLE to that process, then
  • use GetModuleFileNameEx() , GetProcessImageFileName() , or QueryFullProcessImageName() to query the process for its full path and filename.
  • use GetWindowModuleFileName() to query the window for the full path and filename of the module that created it (assuming the intended window is created by an actual EXE and not a DLL used by an EXE).

Once you have the window’s filename, you can then compare that to your target filename.

Return Window handle by it’s name / title

I can’t solve this problem. I get an error:

It sounds very easy and probably is. sorry for asking so obvious questions.

I tried with many different ways and each fails. Thanks in advance.

6 Answers 6

Update: See Richard’s Answer for a more elegant approach.

Don’t forget you’re declaring you hWnd inside the loop — which means it’s only visible inside the loop. What happens if the window title doesn’t exist? If you want to do it with a for you should declare it outside your loop, set it inside the loop then return it.

Or in a more LINQ-y way.

Because you are declaring hWnd inside the if block, it is inaccessible to the return statement which is outside it. See http://www.blackwasp.co.uk/CSharpVariableScopes.aspx for clarification.

The code you’ve provided can be fixed by moving the declaration of the hWnd variable:

Coming several years late to this but, as others have mentioned, the scope of hWnd is only in the foreach loop.

However it’s worth noting that, assuming you’re doing nothing else with the function, then there are two issues with the answers others have provided:

  1. The variable hWnd is actually unnecessary since it’s only being for one thing (as the variable for the return )
  2. The foreach loop is inefficient as, even after you’ve found a match, you continue to search the rest of the processes. In actual fact, it’ll return the last process it finds that matches.

Assuming that you don’t want to match the last process (point #2), then this is a cleaner and more efficient function:

What is a Windows Handle?

What is a «Handle» when discussing resources in Windows? How do they work?

7 Answers 7

It’s an abstract reference value to a resource, often memory or an open file, or a pipe.

Properly, in Windows, (and generally in computing) a handle is an abstraction which hides a real memory address from the API user, allowing the system to reorganize physical memory transparently to the program. Resolving a handle into a pointer locks the memory, and releasing the handle invalidates the pointer. In this case think of it as an index into a table of pointers. you use the index for the system API calls, and the system can change the pointer in the table at will.

Alternatively a real pointer may be given as the handle when the API writer intends that the user of the API be insulated from the specifics of what the address returned points to; in this case it must be considered that what the handle points to may change at any time (from API version to version or even from call to call of the API that returns the handle) — the handle should therefore be treated as simply an opaque value meaningful only to the API.

I should add that in any modern operating system, even the so-called «real pointers» are still opaque handles into the virtual memory space of the process, which enables the O/S to manage and rearrange memory without invalidating the pointers within the process.

A HANDLE is a context-specific unique identifier. By context-specific, I mean that a handle obtained from one context cannot necessarily be used in any other aribtrary context that also works on HANDLE s.

For example, GetModuleHandle returns a unique identifier to a currently loaded module. The returned handle can be used in other functions that accept module handles. It cannot be given to functions that require other types of handles. For example, you couldn’t give a handle returned from GetModuleHandle to HeapDestroy and expect it to do something sensible.

The HANDLE itself is just an integral type. Usually, but not necessarily, it is a pointer to some underlying type or memory location. For example, the HANDLE returned by GetModuleHandle is actually a pointer to the base virtual memory address of the module. But there is no rule stating that handles must be pointers. A handle could also just be a simple integer (which could possibly be used by some Win32 API as an index into an array).

HANDLE s are intentionally opaque representations that provide encapsulation and abstraction from internal Win32 resources. This way, the Win32 APIs could potentially change the underlying type behind a HANDLE, without it impacting user code in any way (at least that’s the idea).

Consider these three different internal implementations of a Win32 API that I just made up, and assume that Widget is a struct .

The first example exposes the internal details about the API: it allows the user code to know that GetWidget returns a pointer to a struct Widget . This has a couple of consequences:

  • the user code must have access to the header file that defines the Widget struct
  • the user code could potentially modify internal parts of the returned Widget struct

Both of these consequences may be undesirable.

The second example hides this internal detail from the user code, by returning just void * . The user code doesn’t need access to the header that defines the Widget struct.

The third example is exactly the same as the second, but we just call the void * a HANDLE instead. Perhaps this discourages user code from trying to figure out exactly what the void * points to.

Why go through this trouble? Consider this fourth example of a newer version of this same API:

Notice that the function’s interface is identical to the third example above. This means that user code can continue to use this new version of the API, without any changes, even though the «behind the scenes» implementation has changed to use the NewImprovedWidget struct instead.

The handles in these example are really just a new, presumably friendlier, name for void * , which is exactly what a HANDLE is in the Win32 API (look it up at MSDN). It provides an opaque wall between the user code and the Win32 library’s internal representations that increases portability, between versions of Windows, of code that uses the Win32 API.

Читайте также:  Что такое hard links linux
Оцените статью