I have Windows 8 and Visual Studio 2013.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HWND hWnd = FindWindow(0,(LPCTSTR)"Skype");
if (hWnd == 0)
{
cerr << "Cannot find window" << endl;
}
return 0;
}
The window is called "Skype" TLoginForm in Spy++ so I use the correct name but I get the error message.(Cannot find window) I know there are lot of similar questions but i didn't get answer.
This issue may be that you're just casting a C-string to a T-string, which is probably a wide character string, so it's not going to work. Try this:
HWND hWnd = FindWindow(0,_T("Skype"));
This ensures the string constant is declared with the appropriate default character width that Windows API functions expect.
Related
From a C++ executable on windows, I want to display a FileOpenPicker.
To do this, I need a window to set as the object's owner:
https://learn.microsoft.com/en-us/windows/apps/develop/ui-input/display-ui-objects#winui-3-with-c
But where do I get the HWND from? I need to call Initialize, but the docs assume you have a hWnd already:
folderPicker.as<::IInitializeWithWindow>()->Initialize(hWnd);
My process does not always have a console window, so ::GetConsoleWindow() will not work.
Here's what I have so far by attempting to use CreateWindow. Nothing happens.
// clang-format off
#include <ShObjIdl.h>
#include <Windows.h>
// clang-format on
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Storage.Pickers.h>
#include <iostream>
#include <string>
#include <string_view>
#include <system_error>
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
int main() {
try {
winrt::init_apartment();
winrt::Windows::Storage::Pickers::FileOpenPicker openPicker;
WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L,
GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
L"ImGui Example", NULL};
::RegisterClassEx(&wc);
HWND hwnd = ::CreateWindow(
wc.lpszClassName, L"Dear ImGui DirectX10 Example", WS_OVERLAPPEDWINDOW,
100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
if (!hwnd) {
std::cerr
<< std::error_code(::GetLastError(), std::system_category()).message()
<< "\n";
return 1;
}
openPicker.as<::IInitializeWithWindow>()->Initialize(hwnd);
openPicker.SuggestedStartLocation(
winrt::Windows::Storage::Pickers::PickerLocationId::Desktop);
openPicker.FileTypeFilter().Append(L"*");
openPicker.FileTypeFilter().Append(L".jpeg");
openPicker.FileTypeFilter().Append(L".png");
auto file = openPicker.PickSingleFileAsync().get();
std::string str = winrt::to_string(file.Path());
std::cout << "name: " << str << "\n";
return 0;
} catch (std::exception& e) {
std::cerr << "error: " << e.what() << "\n";
return 1;
}
}
This question appears to be asking a similar thing, but OP solved it with ::GetConsoleWindow(), which is not an option.
Based on empirical evidence, IInitializeWithWindow::Initialize() is happy with just about any top-level window handle. A window handle associated with a process running in the CONSOLE subsystem is commonly available through the GetConsoleWindow API:
openPicker.as<::IInitializeWithWindow>()->Initialize(::GetConsoleWindow());
This produces the desired behavior1 when using the standard command prompt (hosted by ConHost.exe). Launching the same program from a process using a pseudoconsole instead (such as Windows Terminal) things start to get flaky: The FilePicker does show up, but it no longer follows the rules of owned windows. It's hiding behind the host process' window, and doesn't move to the foreground, when the (not actually an) owner is activated.
Whether this is how things should work, or are designed to work, or if any of this is within specification is unclear. None of this is documented, which seems to be the most convenient way to ship interfaces these days.
The fact that FileOpenPicker isn't documented to implement IInitializeWithWindow doesn't exactly help, either. All hail to cloaked interfaces of which there is only anecdotal evidence.
Ranting aside, you'll probably want to use std::wcout in place of std::cout. Otherwise you'll see an address printed rather than a string.
1 Just because you can doesn't necessarily mean you should create a window hierarchy across threads.
I am using the following code to get a list of windows running on my machine
#include <iostream>
#include <windows.h>
using namespace std;
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
TCHAR buffer[512];
SendMessage(hwnd, WM_GETTEXT, 512, (LPARAM)(void*)buffer);
wcout << buffer << endl;
return TRUE;
}
int main()
{
EnumWindows(EnumWindowsProc, NULL);
return 0;
}
I want to get a list of what is normally refered to as a Window - I say this because when running the above code I get a list of around 40 entries, most of these are not what I would call windows.
Here is an excerpt of the output produced by running the above script on my machine, out of the 5 entries only Microsoft Visual Studio is a Window
...
Task Switching
Microsoft Visual Studio
CiceroUIWndFrame
Battery Meter
Network Flyout
...
How can I go about filtering/parsing this data, as there is not anything to use as an identifier.
I would use EnumDesktopWindows to enumerate all top-level windows in your desktop; you may even use the IsWindowsVisible API during the enumeration process, to filter non-visible windows out.
This compilable C++ code works fine for me (note that here I showed how to pass some additional info to the enumeration proc, in this case using a pointer to a vector<wstring>, in which the window titles are stored for later processing):
#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
using std::vector;
using std::wcout;
using std::wstring;
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
if (!IsWindowVisible(hwnd))
{
return TRUE;
}
wchar_t titleBuf[512];
if (GetWindowText(hwnd, titleBuf, _countof(titleBuf)) > 0)
{
auto pTitles = reinterpret_cast<vector<wstring>*>(lParam);
pTitles->push_back(titleBuf);
}
return TRUE;
}
int main()
{
vector<wstring> titles;
EnumDesktopWindows(nullptr, EnumWindowsProc, reinterpret_cast<LPARAM>(&titles));
for (const auto& s : titles)
{
wcout << s << L'\n';
}
}
Define what you call a Window and query the windows handle for the correct properties. Use GetWindowLong() with for example GWL_HWNDPARENT to test if there's no parent window or if the parent window is the desktop window. Additional test may be needed, e.g. you can use the (extended) window styles. See also here for additional ideas on usable tests.
Hi I have to run a program in C++ and I want to make sure when the program is executed, it opens the console in a particular size/dimensions, so that the display in my program is proper. I need help as I don't know how to do it. I am using Dev C++ 5.42(Orwell). I tried using
#include<iostream>
#include<windows.h>
using namespace std;
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
int main(){
cout<<"Hello World";
}
and got an error
[Error] expected constructor, destructor, or type conversion before '(' token
I'm a beginner and hence I don't know much about these things.
That function is useless for console applications, which don't own a window (unless they create one using the CreateWindow API, which is atypical for console apps). Instead their output is connected to csrss, which does have windows.
You should be using
SetConsoleScreenBufferSize
SetConsoleWindowInfo
instead.
There's an example at http://www.cplusplus.com/forum/windows/10731/
This works for me:
HWND hwnd = GetConsoleWindow();
if( hwnd != NULL ){ MoveWindow(hwnd ,340,550 ,680,150 ,TRUE); }
If your looking for changing the screen buffer then :
HANDLE buff = GetStdHandle(STD_OUTPUT_HANDLE);
COORD sizeOfBuff;
sizeOfBuff.X=150;
sizeOfBuff.Y=100;
SetConsoleScreenBufferSize(buff,sizeOfBuff);
To resize the screen use DaveWalley's solution.
Or you could do this (only for resizing)
HWND hwnd = GetConsoleWindow();
if( hwnd != NULL ){ SetWindowPos(hwnd ,0,0,0 ,1000,300 ,SWP_SHOWWINDOW|SWP_NOMOVE); }
Be sure to include:
#define _WIN32_WINNT 0x0502
#include<windows.h>
at the begining of the file. Literally as the first lines.
Got the solution by reding about the functions mentioned by Ben Voigt.
This is not a complex question. I'm having trouble finding the handle that belongs to iTunes. But although iTunes is running in the background, it keeps telling me it can't find the window. So I went on checking whether I miss typed the window name, but spy++ pointed out to me that I was using the correct window name and class name (see below). I'm sure it's a small mistake but I can't seem to find it. Does anyone have an insight? Thanks in advance.
HWND hwnd;
hwnd = FindWindow((LPCWSTR)"iTunes",(LPCWSTR)"iTunes");
if (hwnd != 0){
cout << "WINDOW FOUND" << endl;
} else {
cout << "WINDOW NOT FOUND" << endl;
cout << hwnd << endl;
}
You are using ANSI strings with what appears to be the Unicode version of FindWindow.
Many Win32 functions are actually a pair of function and a macro. For example, FindWindow is defined approximately like this:
HWND WINAPI FindWindowA(LPCSTR lpClassName, LPCSTR lpWindowName);
HWND WINAPI FindWindowW(LPCWSTR lpClassName, LPCWSTR lpWindowName);
#if (UNICODE)
# define FindWindow FindWindowW
#else
# define FindWindow FindWindowA
#endif
Try explicitely calling FindWindowA or using wide strings like this:
HWND hwnd = FindWindow(L"iTunes", L"iTunes");
I am attempting to hide a 3rd part window on bootup of our computers. I am using the following code.
#include<windows.h>
#include <stdio.h>
int main() {
char windowName[500];
HWND window = FindWindow("WindowClassAsReportedByWindowSpy++", NULL);
//GetWindowText(window, windowName, 63);
ShowWindow(firefox,SW_HIDE);
getchar();
return 0;
}
The only problem is the window will not hide. Any ideas on why this isn't working /how I could accomplish this differently.
Most likely your program calls FindWindow before the target window is created, and so doesn't find it.
You'll need to sleep and retry the find.
You probably want to do sanity checks to make sure FindWindow is not returning NULL. Even better, call FindWindow in a loop until it doesn't return NULL.
#include <windows.h>
#include <stdio.h>
static const wchar_t g_cszFirefoxClass[] = L"firefox";
int __cdecl wmain(__in int argc, __in_ecount_z_opt(argc) wchar_t* _wargv[], __in_z_opt __wenviron[])
{
UNREFERENCED_PARAMETER(argc);
UNREFERENCED_PARAMETER(_wargv);
UNREFERENCED_PARAMETER(__wenviron);
HWND hWnd;
do {
hWnd = FindWindow(g_cszFirefoxClass, NULL);
Sleep(100);
} while (hWnd == NULL);
wprintf(L"[-] Firefox found! [HWND = 0x%X]\n", hWnd);
if (ShowWindow(hWnd, SW_HIDE))
{
wprintf(L"[-] Successfully hid Firefox window!\n");
return EXIT_SUCCESS;
}
else
{
fwprintf(stderr, L"[x] Failed to hide Firefox window..\n");
return EXIT_FAILURE;
}
}