Getting HWND of current Process - c++

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

Related

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

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.

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.

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.

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