Win32 程式設計中,視窗全螢幕化可在三個時機處理,核心 API 為 GetSystemMetrics、GetDesktopWindow、GetWindowRect、SetWindowLong、SetWindowPos。
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) {
HWND hWnd;
hInst = hInstance;
UINT width = GetSystemMetrics(SM_CXSCREEN);
UINT height = GetSystemMetrics(SM_CYSCREEN);
hWnd = CreateWindow(szWindowClass, szTitle, WS_POPUP,
0, 0, width, height,
NULL, NULL, hInstance, NULL);
if (!hWnd) return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
WS_POPUP 樣式(無標題列/邊框),座標 (0,0) 寬高設為螢幕解析度。BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) {
HWND hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
NULL, NULL, hInstance, NULL);
if (!hWnd) return FALSE;
HWND hDesk = GetDesktopWindow();
RECT rc; GetWindowRect(hDesk, &rc);
SetWindowLong(hWnd, GWL_STYLE, WS_BORDER); // 只保留邊框或改 WS_POPUP
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, rc.right, rc.bottom, SWP_SHOWWINDOW);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
// 在視窗程序 WndProc 中處理 WM_KEYDOWN
case WM_KEYDOWN:
switch (wParam) {
case VK_ESCAPE: {
HWND hDesk = GetDesktopWindow();
RECT rc; GetWindowRect(hDesk, &rc);
SetWindowLong(hWnd, GWL_STYLE, WS_BORDER);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, rc.right, rc.bottom, SWP_SHOWWINDOW);
} break;
}
return 0;
SetWindowPos 套用,且 HWND_TOPMOST 確保置頂。三種時機涵蓋大多數應用場景,依需求選擇。