![](/img/trans.png)
[英]How to terminate windows sockets when internet is down? (C++ WinAPI)
[英]How can I make the application run when it refuses to terminate, and text messages about completion attempts (WinAPI C++) are displayed in the window?
主要任務如下所示:
編寫一個程序,創建一個 window,它有自己的 cursor 和圖標,並在程序結束前附加一個請求。 如果終止失敗,應用程序將繼續運行。 window 顯示有關完成嘗試的文本消息。
如何補充這段代碼? 或者它有什么問題? 如何正確完成這項任務?
#include <Windows.h>
int CALLBACK wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR szCmdLine, int nCmdShow)
{
MSG msg{};
HWND hwnd{};
WNDCLASSEX wc{ sizeof(WNDCLASSEX) };
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH));
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
wc.hIconSm = LoadIcon(nullptr, IDI_APPLICATION);
wc.hInstance = hInstance;
wc.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) ->LRESULT
{
switch (uMsg)
{
case WM_CLOSE:
switch (MessageBox(hWnd, L"Are you sure you want to get out?", L"", MB_YESNO))
{
case IDYES:
DestroyWindow(hWnd);
break;
case IDNO:
??????????????
}
case WM_DESTROY:
{
PostQuitMessage(EXIT_SUCCESS);
}
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
};
wc.lpszClassName = L"MyAppClass";
wc.lpszMenuName = nullptr;
wc.style = CS_VREDRAW | CS_HREDRAW;
if (!RegisterClassEx(&wc))
return EXIT_FAILURE;
if (hwnd = CreateWindow(wc.lpszClassName, L"", WS_OVERLAPPEDWINDOW, 0, 0, 1200, 1500, nullptr, nullptr, wc.hInstance, nullptr), hwnd == INVALID_HANDLE_VALUE)
return EXIT_FAILURE;
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
根據WM_CLOSE
文檔:
如果應用程序處理此消息,它應該返回零。
應用程序可以在銷毀 window 之前通過處理 WM_CLOSE 消息並僅在用戶確認選擇時調用 DestroyWindow function來提示用戶進行確認。
默認情況下, DefWindowProc function 調用 DestroyWindow function來銷毀 window。
因此,如果用戶決定不關閉 window,只需從 window 過程return
即可。
此外,附帶說明一下,您的WM_CLOSE
案例缺少break
語句,因此無論您在其中做什么,代碼最終都會落入WM_DESTROY
案例並在用戶嘗試關閉 window 時調用PostQuitMessage()
。所以你也需要解決這個問題。
試試這個:
wc.lpfnWndProc = [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -> LRESULT
{
switch (uMsg)
{
case WM_CLOSE:
if (MessageBox(hWnd, L"Are you sure you want to get out?", L"", MB_YESNO) != IDYES)
{
// TODO: display text message about completion attempt...
return 0;
}
break;
case WM_DESTROY:
PostQuitMessage(EXIT_SUCCESS);
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.