gpt4 book ai didi

c++ - 如何在没有窗口的情况下防止系统关闭?

转载 作者:搜寻专家 更新时间:2023-10-31 01:30:31 24 4
gpt4 key购买 nike

我有带有此源代码的 Windows 应用程序

#include <Windows.h>
#include <thread>
#include <chrono>

int WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int cmdShow)
{
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

return msg.wParam;
}
LRESULT CALLBACK WinProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
switch (Message)
{
case WM_QUERYENDSESSION:
MessageBox(NULL, "Triggered?", "Message", 0);
AbortSystemShutdown(NULL);
return 0;

default:
return DefWindowProc(hWnd, Message, wParam, lParam);
}

return 0;
}

我需要知道系统何时关闭并阻止它,或者至少向用户发送消息。

我的应用程序似乎没有收到 WM_QUERYENDSESSION 消息。

我也尝试过使用 ShutdownBlockReasonCreate() 但我没有用于窗口的 HWND

我应该怎么做?

最佳答案

WM_QUERYENDSESSION 的引用资料中所述:

A window receives this message through its WindowProc function.

你有一个 WindowProc 但你缺少一个窗口。 WindowProc 必须与窗口相关联,否则 Windows 不知道它。要将 WindowProc 与窗口相关联,您可以调用 RegisterClassEx,然后调用 CreateWindowEx。在对 CreateWindowEx 的调用中指定新创建的窗口类的名称。

窗口必须是顶层窗口。它可以是不可见的,但在这种情况下适用以下内容(来自 Application Shutdown Changes in Windows Vista ):

Also note that if your application has no visible top-level windows,it must use this API [ShutdownBlockReasonCreate()] if it needs to successfully block shutdown. Suchapplications will automatically be terminated if they block shutdownwithout using the API.

请注意 message-only window will not receive WM_QUERYENDSESSION .

工作示例:

#include <windows.h>

LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam );

int APIENTRY wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPWSTR lpCmdLine, int nCmdShow )
{
WNDCLASSEXW wx = { sizeof(wx) }; // set cbSize member and zero-initialize all other
wx.lpfnWndProc = WndProc;
wx.hInstance = hInstance;
wx.lpszClassName = L"MyWindowClass";

if( ! RegisterClassExW( &wx ) )
return 1; // TODO: improve error handling

HWND hWnd = CreateWindowExW( 0, wx.lpszClassName, L"My Application", 0, 0, 0, 0, 0,
NULL, NULL, NULL, NULL );
if( ! hWnd )
return 2; // TODO: improve error handling

MSG msg;
while( GetMessage( &msg, nullptr, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}

return static_cast<int>( msg.wParam );
}

LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
switch( message )
{
case WM_QUERYENDSESSION:
{
// Try to block shutdown.
ShutdownBlockReasonCreate( hWnd, L"I don't want to sleep (yet)!" );
return FALSE;
}
case WM_ENDSESSION:
{
// TODO: Always handle this message because shutdown can be forced
// even if we return FALSE from WM_QUERYENDSESSION!
return 0;
}
default:
{
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
return 0;
}

进一步阅读:

关于c++ - 如何在没有窗口的情况下防止系统关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47767786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com