How can I get EnumWindows to list all windows? - c++

I'm assuming, what I'm asking should actually be the default, but I'm experiencing some behavior I don't understand.
#include "stdafx.h"
using namespace std;
BOOL CALLBACK enumWindowsProc(
__in HWND hWnd,
__in LPARAM lParam
) {
if( !::IsIconic( hWnd ) ) {
return TRUE;
}
int length = ::GetWindowTextLength( hWnd );
if( 0 == length ) return TRUE;
TCHAR* buffer;
buffer = new TCHAR[ length + 1 ];
memset( buffer, 0, ( length + 1 ) * sizeof( TCHAR ) );
GetWindowText( hWnd, buffer, length + 1 );
tstring windowTitle = tstring( buffer );
delete[] buffer;
wcout << hWnd << TEXT( ": " ) << windowTitle << std::endl;
return TRUE;
}
int _tmain( int argc, _TCHAR* argv[] ) {
wcout << TEXT( "Enumerating Windows..." ) << endl;
BOOL enumeratingWindowsSucceeded = ::EnumWindows( enumWindowsProc, NULL );
cin.get();
return 0;
}
If I invoke that code, it will list all minimized windows:
Now, I'm no longer interested in only the minimized windows, now I want all of them. So I remove the IsIconic check:
BOOL CALLBACK enumWindowsProc(
__in HWND hWnd,
__in LPARAM lParam
) {
/*
if( !::IsIconic( hWnd ) ) {
return TRUE;
}
*/
int length = ::GetWindowTextLength( hWnd );
if( 0 == length ) return TRUE;
TCHAR* buffer;
buffer = new TCHAR[ length + 1 ];
memset( buffer, 0, ( length + 1 ) * sizeof( TCHAR ) );
GetWindowText( hWnd, buffer, length + 1 );
tstring windowTitle = tstring( buffer );
delete[] buffer;
wcout << hWnd << TEXT( ": " ) << windowTitle << std::endl;
return TRUE;
}
Now I get all windows except the minimized ones (none of the previously listed window handles are listed this time):
For completeness, this is the stdafx.h:
#pragma once
#include "targetver.h"
#include <iostream>
#include <map>
#include <string>
namespace std {
#if defined _UNICODE || defined UNICODE
typedef wstring tstring;
#else
typedef string tstring;
#endif
}
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <psapi.h>
What am I doing wrong?

Here is a callback function that lists all open windows:
#include <string>
#include <iostream>
#include <Windows.h>
static BOOL CALLBACK enumWindowCallback(HWND hWnd, LPARAM lparam) {
int length = GetWindowTextLength(hWnd);
char* buffer = new char[length + 1];
GetWindowText(hWnd, buffer, length + 1);
std::string windowTitle(buffer);
delete[] buffer;
// List visible windows with a non-empty title
if (IsWindowVisible(hWnd) && length != 0) {
std::cout << hWnd << ": " << windowTitle << std::endl;
}
return TRUE;
}
int main() {
std::cout << "Enmumerating windows..." << std::endl;
EnumWindows(enumWindowCallback, NULL);
std::cin.ignore();
return 0;
}
If you want to check if the window is minimized, you can use IsIconic().
See Also:
Microsoft: EnumWindows function
Stack Overflow: Getting a list of all open windows in c++ and storing them

Well, wcout.flush() never works, however wcout.clear() fixes your code, at least for me.
wcout << hWnd << TEXT( ": " ) << windowTitle << std::endl;
wcout.clear();
return TRUE;
And I know that this question is already one year old, however it's never too late to answer.

It's (as I assumed) not a problem with EnumWindows at all. The problem is with the output stream.
While debugging, I noticed that enumWindowsProc is called just fine for every window, but that some iterations are simply not generating output.
For the time being, I switched to using _tprintf, but I don't understand what the problem with the original code is. Calling wcout.flush() had no desirable effect either.

Documentation of Windows (dunno its accuracy) says that EnumWindows only enumerates top level windows. If you wish to enumerate child windows, you need to use EnumChildWindows function where you have to pass handle of parent window

Related

C++ Win API - FindWindow() or EnumWindows() to retrieve specific windows

I have the following problem with retrieving the window handle from a specific window (title and class name are known):
There are two identical windows with different handles under two different processes, but FindWindow() can find the handle only from the newest window spawned, never from the first one.
What can be used instead? Can EnumWindows() be used to retrieve a list of windows with the same characteristics?
Use the Win32 API EnumWindows , and then check which process each window belongs to by using the Win32 API GetWindowThreadProcessId.
Here is a sample:
#include <iostream>
#include <Windows.h>
using namespace std;
BOOL CALLBACK enumProc(HWND hwnd, LPARAM) {
TCHAR buf[1024]{};
GetClassName(hwnd, buf, 100);
if (!lstrcmp(buf, L"Notepad"))
{
GetWindowText(hwnd, buf, 100);
DWORD pid = 0;
GetWindowThreadProcessId(hwnd, &pid);
wcout << buf << " " << pid << endl;
}
return TRUE;
}
int main() {
EnumWindows(&enumProc, 0);
}
If you need to check the window of each process, you can refer to this answer.
typedef struct
{
const char *name;
const char *class;
HWND handles[10];
int handlesFound;
} SearchWindowInfo;
SearchWindowInfo wi;
wi.handlesFound = 0;
wi.title = "WindowName";
wi.class = "ClassName";
BOOL CALLBACK searchWindowCallback(HWND hwnd, LPARAM lParam)
{
SearchWindoInfo *wi = (SearchWindoInfo *)lParam;
char buffer[256];
if (wi->handlesFound == 10)
return FALSE;
buffer[255] = 0;
if (wi->name)
{
int rc = GetWindowText(hwnd, buffer, sizeof(buffer)-1);
if(rc)
{
if (strcmp(wi->name, buffer) == 0)
{
wi->handles[wi->handlesFound++] = hwnd;
return TRUE;
}
}
}
if (wi->class)
{
int rc = GetClassName (hwnd, buffer, sizeof(buffer)-1);
if(rc)
{
if (strcmp(wi->class, buffer) == 0)
{
wi->handles[wi->handlesFound++] = hwnd;
return TRUE;
}
}
}
return TRUE;
}
EnumWindows(searchWindowCallback, (LPARAM)&wi);
for(int i = 0; i < wi.handlesFound; i++)
{
// yeah...
}

GetModuleFileNameEx is returning 0 and GetLastError returns Overflow error. What am I doing wrong?

So today I decided to mess a bit with windows.h and I thought of a little exercise to practise, this is the code I wrote, but it's giving me headaches.
It keeps returning 0, so no name is being passed into ExecName, and the error I get if I lookup with GetLastError() is Overflow error.
I've tried different methods of getting the executables' names but it always ends the same.
#include <iostream>
#include <Windows.h>
#include <Psapi.h>
TCHAR* ExeToFind = "Discord.exe";
BOOL CALLBACK CB_EW(
_In_ HWND hwnd,
_In_ LPARAM lParam
)
{
TCHAR ExecName[MAX_PATH];
DWORD ProcesID = NULL;
GetWindowThreadProcessId(hwnd, &ProcesID);
HANDLE handle = OpenProcess(NULL, false, ProcesID);
if (GetModuleFileNameEx(handle, NULL, ExecName, MAX_PATH) == 0) {
std::cout << "Error " << GetLastError();
return true;
}
//GetWindowText(hwnd, ExecName, GetWindowTextLength(hwnd)+1);
//GetProcessImageFileName(hwnd, ExecName, MAX_PATH);
std::cout << ExecName;
if (ExecName == ExeToFind) {
std::cout << "Here it is\n";
return false;
}
else {
std::cout << "next\n";
return true;
}
}
int main()
{
//HWND hWnd = FindWindow(0,0);
EnumWindows(CB_EW, NULL);
while (true) {
}
return 0;
}
What am I doing wrong?
It was a permission issue, instead of using NULL for the access permission on OpenProcess, I used MAXIMUM_ALLOWED and it worked

Issue when enumerating windows

I'm having a problem when trying to run the following code:
#include "header.h"
int main()
{
id = GetCurrentProcessId();
EnumWindows(hEnumWindows, NULL);
Sleep(5000);
//MoveWindow(hThis, 450, 450, 100, 100, TRUE);
system("pause");
return 0;
}
//header.h
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <Windows.h>
using namespace std;
DWORD id = 0;
HWND hThis = NULL;
BOOL CALLBACK hEnumWindows(HWND hwnd, LPARAM lParam)
{
DWORD pid = 0;
pid = GetWindowThreadProcessId(hwnd, NULL);
if (pid == id)
{
hThis = GetWindow(hwnd, GW_OWNER);
if (!hThis)
{
cout << "Error getting window!" << endl;
}
else
{
char *buffer = nullptr;
int size = GetWindowTextLength(hThis);
buffer = (char*)malloc(size+1);
if (buffer != nullptr)
{
GetWindowText(hThis, buffer, size);
cout << pid << ":" << buffer << endl;
free(buffer);
}
}
}
return TRUE;
}
When I run this code nothing is output to the screen almost as if the program is not attached. I tried running it under a console and windows subsystem in VS2013.
According to the GetCurrentProcessId docs, the API
Retrieves the process identifier of the calling process.
GetWindowThreadProcessId, on the other hand,
Retrieves the identifier of the thread that created the specified window and, optionally, the identifier of the process that created the window.
The return value is the identifier of the thread that created the window.
So looking at your call:
pid = GetWindowThreadProcessId(hwnd, NULL);
You're actually getting back a thread ID, not a process ID. So when you compare pid to id, you're comparing a process ID and a thread ID, and that's just not going to work. Try this instead:
GetWindowThreadProcessId(hwnd, &pid);
(Note: I can't actually test whether this works, since EnumWindows requires a top-level window to enumerate and I ran this as a console app. Let me know if this answer doesn't work for you and I'll delete it.)
(As a second note, you don't need to use NULL anymore, even for WinAPI stuff like HWND. nullptr will work perfectly fine.)
I assume you're trying to find the "Main" window from the ProcessID.. In that case, this MAY help:
#include "stdafx.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <Windows.h>
struct WindowHandleStructure
{
unsigned long PID;
HWND WindowHandle;
};
BOOL CALLBACK EnumWindowsProc(HWND WindowHandle, LPARAM lParam)
{
unsigned long PID = 0;
WindowHandleStructure* data = reinterpret_cast<WindowHandleStructure*>(lParam);
GetWindowThreadProcessId(WindowHandle, &PID);
if (data->PID != PID || (GetWindow(WindowHandle, GW_OWNER) && !IsWindowVisible(WindowHandle)))
{
return TRUE;
}
data->WindowHandle = WindowHandle;
return FALSE;
}
HWND FindMainWindow(unsigned long PID)
{
WindowHandleStructure data = { PID, nullptr };
EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(&data));
return data.WindowHandle;
}
int main()
{
HWND Window = FindMainWindow(GetCurrentProcessId());
std::wstring Buffer(GetWindowTextLength(Window) + 1, L'\0');
GetWindowText(Window, &Buffer[0], Buffer.size());
std::wcout << Buffer.c_str() << L"\n";
system("pause");
return 0;
}

Use wildcards with FindWindow api call with mfc

I am using FindWindow in an mfc application.
HWND hWnd = ::FindWindow(NULL, _T("foobar v5"));
I would like to use FindWindow with wildcards so that I can match just foobar.
Thanks
You will have to create your own implementation which should be based on EnumWindows, GetWindowText and GetWindowTextLength which then must allow the wildcards.
#include <Windows.h>
#include <iostream>
#include <string>
#include <vector>
struct FindWindowData {
FindWindowData( TCHAR const * windowTitle )
: WindowTitle( windowTitle )
, ResultHandle( 0 )
{}
std::basic_string<TCHAR> WindowTitle;
HWND ResultHandle;
};
BOOL CALLBACK FindWindowImpl( HWND hWnd, LPARAM lParam ) {
FindWindowData * p = reinterpret_cast<FindWindowData*>( LongToPtr( lParam ) );
if( !p ) {
// Finish enumerating we received an invalid parameter
return FALSE;
}
int length = GetWindowTextLength( hWnd ) + 1;
if( length > 0 ) {
std::vector<TCHAR> buffer( std::size_t( length ), 0 );
if( GetWindowText( hWnd, &buffer[0], length ) ) {
// Comparing the string - If you want to add some features you can do it here
if( _tcsnicmp( &buffer[0], p->WindowTitle.c_str(), min( buffer.size(), p->WindowTitle.size() ) ) == 0 ) {
p->ResultHandle = hWnd;
// Finish enumerating we found what we need
return FALSE;
}
}
}
// Continue enumerating
return TRUE;
}
// Returns the window handle when found if it returns 0 GetLastError() will return more information
HWND FindWindowStart( TCHAR const * windowTitle ) {
if( !windowTitle ) {
SetLastError( ERROR_INVALID_PARAMETER );
return 0;
}
FindWindowData data( windowTitle );
if( !EnumWindows( FindWindowImpl, PtrToLong(&data) ) && data.ResultHandle != 0 ) {
SetLastError( ERROR_SUCCESS );
return data.ResultHandle;
}
// Return ERROR_FILE_NOT_FOUND in GetLastError
SetLastError( ERROR_FILE_NOT_FOUND );
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "HWND: " << FindWindowStart(TEXT("foobar ") );
std::cout << " GetLastError() = " << GetLastError() << std::endl;
return 0;
}
Unfortunately, FindWindow() does not support wildcards.
Did you try matching the window class name instead of its title? You can use a tool like Spy++ to find out the class name of the foobar main window.

Is it possible to use Win32 Hooks in Qt applications

I like to know if its possible to use win32 keyboard hook function (SetWindowsHookEx , SetWindowsHookEx ) in a Qt application.
If possible pls provide a sample code on using SetWindowsHookEx , SetWindowsHookEx functions in Qt.
//Update as of 18 Feb 2010 //
I havent figured out how to do that in QT yet.
But as a workaround I have created a win32 dll using vc++ express edition and placed my hook commands inside the dll functions.
And I call that dll functions from Qt using QLibrary class
/* hearder file code*/
QLibrary *myLib;
typedef HHOOK (*MyPrototype)(HINSTANCE);
/* source file code */
myLib = new QLibrary( "ekhook.dll" );
MyPrototype myFunction;
myFunction = (MyPrototype) myLib->resolve( "Init" );
init() is the function in ekhook.dll thats being called
I was wondering the same thing and found this finally.. Credit goes to Voidrealms.
The video explains enough to make a working application with the following code below.
//Copied Code from YouTube Video
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QTime>
#include <QChar>
#include <iostream>
#include <windows.h>
#pragma comment(lib, "user32.lib")
HHOOK hHook = NULL;
using namespace std;
void UpdateKeyState(BYTE *keystate, int keycode)
{
keystate[keycode] = GetKeyState(keycode);
}
LRESULT CALLBACK MyLowLevelKeyBoardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
//WPARAM is WM_KEYDOWn, WM_KEYUP, WM_SYSKEYDOWN, or WM_SYSKEYUP
//LPARAM is the key information
qDebug() << "Key Pressed!";
if (wParam == WM_KEYDOWN)
{
//Get the key information
KBDLLHOOKSTRUCT cKey = *((KBDLLHOOKSTRUCT*)lParam);
wchar_t buffer[5];
//get the keyboard state
BYTE keyboard_state[256];
GetKeyboardState(keyboard_state);
UpdateKeyState(keyboard_state, VK_SHIFT);
UpdateKeyState(keyboard_state, VK_CAPITAL);
UpdateKeyState(keyboard_state, VK_CONTROL);
UpdateKeyState(keyboard_state, VK_MENU);
//Get keyboard layout
HKL keyboard_layout = GetKeyboardLayout(0);
//Get the name
char lpszName[0X100] = {0};
DWORD dwMsg = 1;
dwMsg += cKey.scanCode << 16;
dwMsg += cKey.flags << 24;
int i = GetKeyNameText(dwMsg, (LPTSTR)lpszName, 255);
//Try to convert the key information
int result = ToUnicodeEx(cKey.vkCode, cKey.scanCode, keyboard_state, buffer, 4, 0, keyboard_layout);
buffer[4] = L'\0';
//Print the output
qDebug() << "Key: " << cKey.vkCode << " " << QString::fromUtf16((ushort*)buffer) << " " << QString::fromUtf16((ushort*)lpszName);
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, MyLowLevelKeyBoardProc, NULL, 0);
if (hHook == NULL)
{
qDebug() << "Hook Failed" << endl;
}
return a.exec();
}
You don't need to do anything with Qt. Just follow the windows examples:
http://msdn.microsoft.com/en-us/library/ms644960(VS.85).aspx
I believe it is possible, yes. Use QWidget::winId.