Validate HWND using Win32 API - c++

From the native Win32 API using C++ is there a way to determine whether the window associated with an HWND is still valid?

You could use the Win32 API IsWindow.
It is not recommended to use it though for 2 reasons:
Windows handles can be re-used once the window is destroyed, so you don't know if you have a handle to an entirely different window or not.
The state could change directly after this call and you will think it is valid, but it may really not be valid.
From MSDN (same link as above):
A thread should not use IsWindow for a
window that it did not create because
the window could be destroyed after
this function was called. Further,
because window handles are recycled
the handle could even point to a
different window.
What can be done?
Perhaps your problem can be re-architected so that you do not have the need to check for a valid handle. Maybe for example you can establish a pipe from the client to the server.
You could also create a windows hook to detect when certain messages occur, but this is probably overkill for most needs.

This question is old, but I needed this functionality myself and was a bit disappointed after reading about the caveats. However, after doing a bit more digging it seems that all is well. Unless you're dealing with 16bit programs, IsWindow appears to be the way to go. The problem of handle re-use appears to have been sufficiently addressed according to this:
http://blogs.msdn.com/b/oldnewthing/archive/2007/07/17/3903614.aspx
So, because of the upper 16bit reuse counter, it is highly unlikely that you'll run into a window reuse problem.

You can use IsWindow() or also try to send the window a WM_NULL message with SendMessage(hWnd, WM_NULL) and see if it is successful.
Also, it is true that the window could be destroyed at any time if it isn't under your control. As others have stated the handle could potentially belong to another window as the handles are reused. In reality I don't know how likely that is.
The only solution that I know of the to create a system wide hook that looks for messages indicating a window is destroyed (WM_CLOSE, WM_DESTROY). Then you would compare the message window handle to ones you are holding to see if any of the windows you care about are affected. See here for more information on system wide hooks.

Maybe a combination of IsWindow, FindWindow and GetWindowThreadProcessId will be more accurate
HWND windowHandle = FindWindow(NULL, TEXT("window_title"));
LPDWORD oldpid = 0;
GetWindowThreadProcessId(windowHandle, &oldpid);
//after some time
if (IsWindow(windowHandle))
{
LPDWORD newpid = 0;
GetWindowThreadProcessId(windowHandle, &newpid);
if (newpid == oldpid)
{
//the window is still running
}else
{
//the window exists but has changed
}
}

If the window procedure for the window in question is under your control (or if you can subclass it), then I would suggest registering a custom message that the window responds to with a non-zero result. Sending that message to any other window (or an invalid HWND) will result in 0.
Of course, that only tells you if the HWND refers to one of the windows that you control -- but perhaps given other answers above that might even be advantageous.
Use RegisterWindowMessage to register the message, using a sufficiently unique name.

if(IsWindow(FindWindow(NULL , TEXT("Example Window Name")))){
// do stuff
}
will check if the window exists and has the appropriate name

Related

which window is on top on the other

I have 2 windows and I want to know which window is on the top of the other?
I tried to test using GetWindowLong and comparing the results but no chance.
LONG wndState1 = ::GetWindowLong(handler1, GWL_EXSTYLE);
LONG wndState2 = ::GetWindowLong(handler2, GWL_EXSTYLE);
both results is equal to 256.
Edited: In the picture below I have the dialog of notepad++ is on top of the FileZilla, How do I Get That by Code.
Is there a trick for that ?
THank you
GetWindowLong is used to retrieve style information for a particular window.
In order to get the top-most window, use
HWND WINAPI GetForegroundWindow(void);
You will still need to know the window handles (HWND) for the processes you're interested in so that you can find out which process owns the foreground window.
Note that this API can only return the window that the user is interacting with (or has interacted with most recently).
UPDATE:
I agree with Remy that there isn't any API to do that. The only way I can think of to actually do that is to install a global hook and intercept certain messages (e.g. WM_ACTIVATE, WM_SETFOCUS and so on). Since you will also retrieve the timestamps for the messages, it should be simple to infer which window is on top of any other window. This will require you to write a dll but this is relatively simple to do. I can't guarantee this will work either though I think it will (I've written a global hook but never used it to find out the z-order of windows)

Getting handle of current window to GetWindowText?

I want to display the Title of the Dialog box:
HWND hWnd = ::GetActiveWindow();
char cc[101];
::GetWindowText(hWnd,cc,100);
MessageBox(cc);
but the result yields a blank "".
not sure what is wrong??
According to MSDN:
Retrieves the window handle to the active window attached to the calling thread's message queue.
This means that if the thread which you are calling the function from doesn't own any window, the function will fail.
You probably want GetForegroundWindow instead.
This may coming a bit late but anyway. If you want to get the current (active) window on the system at any time, the best approach is by using a procedure implemented in a DLL, then installing a global hook that call this procedure.
The following resources are quite helpful:
Creating and using your DLL
An overview on Hooks

C/C++ - Windows - how to keep track of HWND context data

In Windows, suppose you have multiple windows (HWNDs) of the same window class open. How do you keep track of the context data in the window procedure so that, for example, window 1 does not get modified when the user tried to type in window 2?
CreateWindow() does not return until after the WndProc() has been called several times, so you can't simply set the resulting HWND to the context data and do a lookup in the WndProc(); you do need to set it in the WndProc().
WndProc() doesn't directly have the context information passed to it except on window creation messages, but unfortunately window creation messages aren't exactly the first messages to be passed to WndProc(). Nay, I find things such as WM_SIZE, WM_NCSIZE, and even some others are passed before I ever see WM_CREATE.
Storing the HWND in a linked list type of storage mechanism would be inefficient with large amounts of windows: each control in a window is simply another type of window and therefore another HWND of which you need to keep track; after a few hundred controls, searching the linked list for the HWND will be a major bottleneck in the program after a few dozen messages are passed to the program in a short amount of time!
From what I hear, some people use SetWindowLong() - but I also hear that some libraries like to use that too to store their own context information separate from the program and that window data collisions can sometimes occur. How can that be avoided?
if I'm understanding you correctly, you want to avoid one window to catch the messages from another. One way to avoid this is to use the solution proposed in this thread, which keeps track of the windows that is created by you and makes sure that the correct windows gets the messages associated to it by storing the pointer for the caller in the GWL_USERDATA .
// ...
m_hWnd = CreateWindowEx(0,"Classname","Title",WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,CW_USEDEFAULT,
320,200,NULL,NULL,hInstance, /*the magic pointer*/ this);
// ...
if(uMsg == WM_CREATE)
{
// collected here..
pParent = (CWindow*)((LPCREATESTRUCT)lParam)->lpCreateParams;
// .. and then stored for later lookup
SetWindowLongPtr(hWnd,GWL_USERDATA,(LONG_PTR)pParent);
}
// ...
You can also catch the WM_NCCREATE message, as proposed by Moo-Juice.
And I don't think you should worry about the messages pre-WM_CREATE, because the window isn't even fully initialized at that point. If you need to set text you do that after the call to CreateWindow(Ex), be it user input or a SendMessagecall.
Whoever creates the window owns that window 100%. If you are the one to call CreateWindow(), then you can use GetWindowLong, knowing that it's yours.
If a library creates the window, however, you can't because it's not yours.
(Aside: Nothing is stopping anyone from stepping on anyone else's toes, but the convention is pretty standard).
If you are using a library that does this, it will generally have some mechanism to associate your own data with a window. Of course, you will need to refer to the documentation for that.
Use Windows properties : SetProp( HWND ,... ) , Getprop( HWND ,... ) and RemoveProp( HWND ,... )
Can't you use WNDCLASS.cbWndExtra to declare whatever private storage your class needs and then it will be allocated by Windows whenever it creates a window of that class.

Getting HWND of current Process

I have a process in c++ in which I am using window API. I want to get the HWND of own process. Kindly guide me how can I make it possible.
If you're talking about getting a process handle, then it's not an HWND (which is a window handle), but a HANDLE (i.e., a kernel object handle); to retrieve a pseudo-handle relative to the current process, you can use GetCurrentProcess as the others explained.
On the other hand, if you want to obtain an HWND (a window handle) to the main window of your application, then you have to walk the existing windows with EnumWindows and to check their ownership with GetWindowThreadProcessId, comparing the returned process ID with the one returned by GetCurrentProcessId. Still, in this case you'd better to save your main window handle in a variable when you create it instead of doing all this mess.
Anyhow, keep always in mind that not all handles are the same: HANDLEs and HWNDs, in particular, are completely different beasts: the first ones are kernel handles (=handles to kernel-managed objects) and are manipulated with generic kernel-handles manipulation functions (DuplicateHandle, CloseHandle, ...), while the second ones are handles relative to the window manager, which is a completely different piece of the OS, and are manipulated with a different set of functions.
Actually, in theory an HWND may have the same "numeric" value of a HANDLE, but they would refer to completely different objects.
Get your console window
GetConsoleWindow();
"The return value is a handle to the window used by the console associated with the calling process or NULL if there is no such associated console."
https://msdn.microsoft.com/en-us/library/windows/desktop/ms683175(v=vs.85).aspx
Get other windows
GetActiveWindow() might NOT be the answer, but it could be useful
"The return value is the handle to the active window attached to the calling thread's message queue. Otherwise, the return value is NULL." > msdn GetActiveWindow() docs
However, the graphical windows are not just popping up - so you should retrieve the handle from the place you/your app've created the window... e.g. CreateWindow() returns HWND handle so all you need is to save&retrieve it...
You are (incorrectly) assuming that a process has only a single HWND. This is not generally true, and therefore Windows can't offer an API to get it. A program could create two windows, and have two HWNDs as a result. OTOH, if your program creates only a single window, it can store that HWND in a global variable.
The GetCurrentProcess() function returns a pseudo-handle which refers to the current process. This handle can be used in most Win32 API functions that take a process handle parameter.
The documentation contains more information about this pseudo-handle, including how to convert it to a real handle if you need to.
You can use HANDLE WINAPI GetCurrentProcess(void); from Kernel32.dll.
See MSDN entry here.
My example is not to deal with process, but maybe you need this:
HWND hwndList = GetDlgItem(hwnd, IDCL_COMBOBOX);
This returns HWND of the control specified by its IDCL_COMBOBOX.
Here is another answer:
this->GetSafeHwnd();

How does GetGuiThreadInfo() work?

I am trying to get the HWND and ThreadID for currently Focussed Window.
Usually GetForegroundWindow() and then then calling GetThreadProcessId() gives me the correct information.
But in Case of IE8 the HWnd the GetForegroundwindow() gives me the HWND of the IE Frame but actually the focussed window (the document object or Internet Explorer_server) is different (running in a different process). So GetForegroundWindow() approach does not work.
So I used GetGuiThreadInfo(DWORD tid) , and passed it the threadId i obtained from GetForegroundWindow.. something like this;
DWORD tid = GetWindowThreadProcessId(GetForegroundWindow(),0);
GetGuiThreadInfo(tid,&guiThreadInfoObject);
HWND focus = guiThreadInfoObject.hwndFocus;
Using the above approach I get the correct HWND for the Internet Explorer_server object which is correct.
However I did not understand , even though the GetGuiThreadInfo() is getting the ThreadId of a thread in a different process which is IE Frame , howcome it is able get me the threadinfo about Internet Explorer_server object which is on a different Process and thread?
Thanks
Getting the window with the focus is pretty easy with GetFocus(). Although I think GetGuiThreadInfo() uses internal data from the window manager. Your approach is liable to fail if IE is minimized or doesn't have the focus.
Use EnumChildWindows() instead, iteratively for each child you find, until you get a window whose GetClassName() call returns "Internet Explorer_Server".
Thanks for bringing this up btw. What IE is doing is expressly forbidden in the docs for SetParent(). I only knew of Acrobat violating this rule, but now you provided evidence of a Microsoft program doing this. That settles it, it is no longer a rule!
GetWindowThreadProcessId retrieves the thread ID that created the (in your case foreground) window.
guiThreadInfoObject.hwndFocus is the window that ha input focus.
There's some leeway here - I haven't found any place that specifically states the foreground window is the one with input focus. (maybe it retrieves already the top level parent/owner?).
Also, AttachThreadInput may slightly change the game - by setting a threads input focus to a window of a different process.
Anyway, since it's not spelled out explicitely, I wouldn't bet my life on that behavior - that means testing on many systems and treating the method as a weak spot that should be improved if possible.