Getting handle of current window to GetWindowText? - c++

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

Related

How to get HWND in win32?

Is there way to get the HWND handler of my window?
I'm using win32.
You could call GetActiveWindow to get the active control in your application, then repeatedly call GetParent on the returned handle until it returns NULL. The last valid handle you get should be the handle of your main window.
The easier way as someone else said is to store the returned value from CreateWindow somewhere.
It's probably good to understand why there is no simple way. It all boils down to "which window?". You'll likely have multiple windows visible on your screen, right now. For instance, the taskbar at the bottom of your screen is a window. even your own app typically has more than one. For instance, the "File Save" dialog is a window. Even the simple MessageBox is a window.
So, how do you identify which window you're talking about? The common answer is that you identify them by their HWND. So, to get the position of the "File Save" dialog window, you ask for the position associated with that HWND. Obviously, you can get any property that way, except the HWND itself ! It makes sense to ask the X/Y position of HWND(0x5e21), but it's stupid to ask which HWND belongs to HWND(0x5e21).
Now, it may happen that you have another more-or-less unique property and you want to get the HWND from that. For instance, you may have an X/Y position. In that case, WindowFromPoint(xy) will return the HWND at that position.
But the most common case is that you need to react to a Windows message for your window. In that case, you get the HWND of your window as the first argument of your WindowProc().
So, unless you tell us what unique information you do have, we can't tell you how to find the matching HWND.
Didn't you create your window via CreateWindow() or CreateWindowEx()? The CreateWindowEx() function and the CreateWindow() function both return the HWND of the newly created window.
Also, the operating system passes you the HWND of your window(s) via your window procedure. It's not a function that you call; it's a function that the operating system calls to let your application do any processing that's needed.

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();

Validate HWND using Win32 API

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

Globally intercept window movement

I am having trouble getting a global system hook to work. I want to be notified whenever a window is moving, as early as possible, and change the window size. This means the CBT hook HCBT_MOVESIZE won't cut it, it only happens after the window has been moved. I want to hook the actual movement of the window, and be able to change the window size during the move.
The hooks are set from a DLL, and the callback function is within that DLL. This is what I've tried.
WH_CALLWNDPROC. It does alert me when a window is moved (WM_MOVING is received for windows from other applications), but I cannot change the contents of the message.
WH_CALLWNDPROCRET Same as WH_CALLWNDPROC.
CBT hook HCBT_MOVESIZE. Event happens to late.
WH_GETMESSAGE. Never receive WM_MOVE, WM_MOVING or WM_WINDOWPOSCHANGING. This hook would allow me to change the messages.
Update: Windows event hooks seem to allow me to capture it:
hWinEventHook = SetWinEventHook(EVENT_SYSTEM_MOVESIZESTART,
EVENT_SYSTEM_MOVESIZEEND, NULL, WinEventProc,
0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
However, this creates a different problem: changing the size of the window using SetWindowPos() does not work (it changes size alright, but immediately changes back to its previous size), even though I use SWP_NOSENDCHANGING. Ideas?
Update 2: Subclassing seems to work, however Visual Studio crashes after each program run (so does a lot of other windows). It works well if I place breakpoints and walk through the "unsubclassing", but not when I let the program run by itself. Ideas?
I have a CBT hook (it was there from earlier), and whenever HCBT_ACTIVATE is sent for a new window, I remove any previous subclassing using SetWindowLongPtr() (this has to run on 64-bit as well), and then subclass the new window. If I put a breakpoint anywhere, and immediately resume the session when it breaks, everything works fine. However, when I do not have any breakpoints, Visual Studio crashes when the program exits.
Hm, I would've thought that HCBT_MOVESIZE is precisely what you want, given that the MSDN says this about CBT hooks:
The system calls this function before activating, creating, destroying,
minimizing, maximizing, moving, or sizing a window.
and in particular:
HCBT_MOVESIZE
A window is about to be moved or sized.
(these quotes were taken from http://msdn.microsoft.com/en-us/library/ms644977%28VS.85%29.aspx)
...so I'd have thought that you get the HCBT_MOVESIZE call in time. The hook function which handles HCBT_MOVESIZE is also allowed to return an integer so that the system can determine whether the operation is allowed or should be prevented. Hence, given that the HCBT_MOVESIZE hook should get an option to prevent the operation, I'd say it's called before the move event occurred.
Are you really sure the hook function is called after the move event? If you do a GetWindowRect call on the particular handle within your hook function, does the returned rect equal the rectangle which is passed to the hook function?
Hooks are pretty heavy. You only want to use them when you absolutely have to.
That said, you could use one of the basic hooks simply as a way to get into the process. Once in the process, you could subclass the window you're interested in and handle the sizing messages in your subclass proc rather than trying to catch everything at the hook level.
Depending on what you want to do in response to the resize, you might need some interprocess communication.

WINAPI: Look at messages from other process

I'm quite new to the Windows API and would like to know how to peek at messages another process receives. As an example, I would like to get the HWND of, say, notepad and peek at all messages that are sent to this window. I code in C/C++.
Thank you
You can use SetWindowsHookEx function, with WH_CALLWNDPROC or some other type of hook, and here is an example.
The WH_CBT can give you great opportunities because you can get a HCBT_CREATEWND code from it and it's sent to you right before a window is created, thus giving you a possibility to provide your own window proc instead of the real one and then be able to get all messages possible with it.
Remember though, greater possibilities also mean greater responsibility. Say you "subclassed" some window, providing your window proc, if your application that set a hook exits, next thing you'll see is the application, whose messages you were peeking at, crashes if you didn't put the address of the original window proc back to where it belongs. The benefit of this kind of hooking is the ability to wait for a certain window (say with a certain window class, or name) to be created and get into that process before any window you're interested in would even be created.
You want to look into SetWindowsHookEx
You are looking for Windows Hooks .
http://msdn.microsoft.com/en-us/library/ms997537.aspx
You can trap SendMessage in the target process using CallWndProc hook procedure.