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.