Difference between HANDLE and HWND in Windows API? - winapi

I'm trying to use function SetForegroundWindow(HWND hWnD). I have some handles but it's not working as parameter of above function. My handle is a thread and I want to run it in foreground.
What are the differences between a HWND and a HANDLE?

They are just abstract data types.
According to MSDN, HANDLE and HWND are defined as:
HANDLE is a handle to an object.
HWND is a handle to a window.
So, a HWND is a HANDLE, but not all HANDLEs are HWND. In fact:
typedef void *PVOID;
typedef PVOID HANDLE;
typedef HANDLE HWND;
Example
You should only pass HWND to SetForegroundWindow unless you know what you are doing.
HWND hWnd = FindWindow(NULL, "Calculator");
SetForegroundWindow(hWnd);
This first gets the handle to a window titled "Calculator" with FindWindow and then brings that window to foreground.

A "handle" is the general term used to refer to a token that identifies a resource on the system (a menu, a DLL module, a block of memory, etc). Often referred to as a "magic cookie", it's normally returned when you first create the resource. You then pass that handle to other functions in the API responsible for processing the resource. You normally need not know what the handle is however. Sometimes it may be a pointer, other times a number, perhaps a structure, or whatever. That's why they hide it using names like HWND which is simply the handle used to identify a window (returned by the API function "CreateWindow()"). You therefore don't convert a "handle" to an HWND and back again since an HWND is already a "handle" (one that merely identifies windows you create).
Found here http://forums.codeguru.com/showthread.php?135438-Handle-and-HWND
You can use FindWindow to get the hwnd from an application http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499(v=vs.85).aspx
This should allow you to get the HWND provided you have the handle to what you're looking for C++ Handle as HWND?

The HWND is also a HANDLE, but a global one.
I.e. a HWND valid in the context of one process is also valid in the context of another process.
Some undocumented info at https://winterdom.com/dev/ui/wnd/.

Related

How to identify the window is belong to a specific process?

Win32 programs have an entry parameter HINSTANCE for the Win32 entry function WinMain(). When you create your own window, the CreateWindow() API call needs this parameter.
My first idea in my mind is that this HINSTANCE should be some unique identify to distinguish different windows belong to different processes. Until recently, in some occasions, I use this HINSTANCE. Wow! If you open the same Win32 program (EXE) twice, each process has the same HINSTANCE value.
Later I figured out, it was some resource identifier (memory address) in the process. It's a virtual address for the process which is related to its PE structure in memory.
Now, if I have the two windows' HWND handles, and I want to check whether the two windows are from the same process, what is the best choice?
You can use the GetWindowThreadProcessId function to retrieve the ID of the process that created a window, given that window's HWND.
Below is a brief C code snippet showing how. We check that the return value of each GetWindowThreadProcessId() call is not zero (see this answer or this blog by Raymond Chen), to ensure that we have passed valid HWND handles.
// win1 and win2 are both HWND handles to check...
DWORD proc1, proc2;
if (!GetWindowThreadProcessId(win1, &proc1)) { // Error (invalid HWND?)
//.. error handling
}
if (!GetWindowThreadProcessId(win2, &proc2)) {
//..
}
if (proc1 == proc2) {
// Windows created by same process
}
else {
// Windows created by different processes
}
GetWindowThreadProcessId can do the work. Record here.
An interactive way to do this would be to use Microsoft's Spy++, which lets you find the Process ID, Thread ID, and parents/children of a window by point-and-clicking its GUI.
You can also find window handles (and plenty of other window-specific data) in this way.

Availability of handles presented in MONITORENUMPROC callback of EnumDisplayMonitors

The MONITORENUMPROC callback function of EnumDisplayMonitors gives me two handles. One of the type HMONITOR and one HDC.
HMONITOR should reference the monitor.
HDC is the handle to the device context of that monitor.
Do I need to release any of those handles before returning from the callback function? If not, how long will they stay around? May I save them for later use?
Do I need to release any of those handles before returning from the
callback function?
No, unless it is explicitly stated in the document to release, like the GetWindowDC function: After painting is complete, the ReleaseDC function must be called to release the device context.
May I save them for later use?
Generally speaking, yes. A physical display has the same HMONITOR as long as it is part of the desktop. When a WM_DISPLAYCHANGE message is sent, any monitor may be removed from the desktop and thus its HMONITOR becomes invalid or has its settings changed. Therefore, an application should check whether all HMONITOR are valid when this message is sent.
HDC handle is from the EnumDisplayMonitors, and its life cycle depends on the HDC parameter in EnumDisplayMonitors.

Do I Need to close the handle if I don't store the return value of GetModuleHandle?

I was wondering if I had to close the handle if for example I were to call GetModuleHandle this way
GetProcAddress(GetModuleHandle("modulename"), "nameoftheexportedfunction")
what would be the proper way to close the handle? Do I need to do
HMODULE hModule = GetModuleHandle("modulename");
GetProcAddress(hModule, "nameoftheexportedfunction")
CloseHandle(hModule);
Or does it get deleted automatically if the value returned by GetModuleHandle isn't stored into a variable?
GetModuleHandle returns an HMODULE (aka HINSTANCE - see What is the difference between HINSTANCE and HMODULE?). This data type cannot be passed to CloseHandle.
The HMODULE could be passed to FreeLibrary but that is not required either, since GetModuleHandle doesn't increase the reference count on the module. In fact, calling FreeLibrary might cause the module to get unmapped prematurely, leading to a spectacular crash.
In short: GetModuleHandle returns a read-only value, that doesn't need to be disposed off in any way. The first line of code in your question is fine.
The Windows API can be very confusing in this respect, as there are multiple things called a handle, and they all have different rules.
In this case, CloseHandle closes kernel handles, which typically refer to files or other kernel resources such as synchronization objects that are created with a name—which all are identified by being returned as a HANDLE.
GetModuleHandle returns an HMODULE—actually the base address of a loaded EXE or DLL—and, as it is not a HANDLE, does not need to be, and must not be, released with CloseHandle.
As #David Heffernan points out, this does not mean other handle types never have their own destroy/release/un-acquire semantics, and it also does not mean that every HANDLE you get from an API must be passed to CloseHandle either. There is just no substitute for knowing the specific API you are dealing with and its particular handle management requirements.

What is the difference between HANDLE and HFILE in WinAPI?

WinAPI OpenFile function returns HFILE, and GetFileTime for instance needs HANDLE. When I feed it with (HANDLE)some_hFile it seems to work fine. Is there any difference in this types, or one of these is simply rudimental?
OpenFile is a 16-bit Windows backward-compatibility function. CreateFile is the function to open files.
If the function succeeds then HFILE is a file HANDLE. If not, then it is an HFILE_ERROR constant (presumably -1). The point is that it can't be a HANDLE on error so they return something that can be either a HANDLE or an error value.
See #Barry's suggestion as well.
To answer your question, HANDLE is just an unsigned 32bit number defined as PVOID. It is a generic handle. HFILE is a specialized handle, although defined as signed 32bit number to be able to get value -1.
There are other specialized handles, like HACCEL, HBITMAP, HINSTANCE, etc., all defined as a dependence to HANDLE.
Years ago, HANDLES were 16-bit ints. All handles everywhere in Windows were HANDLES. Then someone realized that a file HANDLE wasn't quite the same thing as a window HANDLE, and if they were defined differently, say as HFILE and HWND, then maybe developers wouldn't accidentally interchange them as much. (However they were both typedef'ed to int).
Later still, someone realized that if they were defined completely defferently...say as:
typedef struct _hfile {} * HFILE;
typedef struct _hwnd {} * HWND;
then the compiler itself would complain if you used one in place of the other, even if, in reality, each was just a plain old 16-bit (eventually 32-bit) int value.
The OpenFile returns a File Handle if succed or a HFILE_ERROR if it fails.

What's an alternative to GWL_USERDATA for storing an object pointer?

In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put this in the window's user data area via SetWindowLong(hwnd, GWL_USERDATA, this), which allows us to have an MFC-like callback or a tightly integrated WndProc, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems?
SetWindowLongPtr was created to replace SetWindowLong in these instances. It's LONG_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations.
LONG_PTR SetWindowLongPtr(
HWND hWnd,
int nIndex,
LONG_PTR dwNewLong
);
Remember that the constants have changed too, so usage now looks like:
SetWindowLongPtr(hWnd, GWLP_USERDATA, this);
Also don't forget that now to retrieve the pointer, you must use GetWindowLongPtr:
LONG_PTR GetWindowLongPtr(
HWND hWnd,
int nIndex
);
And usage would look like (again, with changed constants):
LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);
MyObject* pMyObject = (MyObject*)lpUserData;
The other alternative is SetProp/RemoveProp (When you are subclassing a window that already uses GWLP_USERDATA)
Another good alternative is ATL style thunking of the WNDPROC, for more info on that, see
http://www.ragestorm.net/blogs/?cat=20
http://www.hackcraft.net/cpp/windowsThunk/

Resources