iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🦁

How to call ShowWindow(hWnd, nCmdShow) from a Windows Console Application

に公開
1

Goal

I want to call ShowWindow to display a window, even when starting with an empty project or a console application in Visual Studio.

Prerequisites

The project properties under [Linker] > [System] > [SubSystem] are set to Console.

Here are the three important things:

main.cpp
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, nullptr, nullptr);
int nCmdShow = SW_NORMAL;
ShowWindow(hWnd, nCmdShow);

According to the reference, the second argument of ShowWindow() should be the value passed from WinMain(), but you can safely ignore this.
It will work perfectly fine with SW_NORMAL or SW_SHOWNORMAL.

References

https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlew
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow

Discussion

YuneKichiYuneKichi

普通にCreateWindowとかすればウィンドウは作れますが……。

  • GetModuleHandleで取得できるのは「モジュールハンドル」
  • ShowWindowの第一引数は「ウインドウハンドル」

です。
モジュールハンドル(kernel32.dll由来)とウインドウハンドル(user32.dll/GDI由来)は別物なので、うまくいっても「たまたま」でしょう。

1