不阻止 Windows 关闭 OnCloseQuery
我有一个应用程序在红十字关闭时隐藏自己。用户可以通过右键单击托盘图标并选择退出来退出它。但它显然会阻止窗口关闭,因此我编写了一个程序来响应 WM_QUERYENDSESSION 以启用关闭,这是相关代码:
procedure TMainForm.OnWindowsEnd(var Msg: TMessage); // responds to message WM_QUERYENDSESSION;
begin
AllowClose:=true;
Close;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose:=AllowClose;
if NOt AllowClose then
Hide;
end;
但奇怪的事情不断发生。当我发出关闭命令时,该应用程序会很好地关闭。但仅此而已。当我第二次关闭时,系统正常退出。 (我正在WinXP 中测试这个)。
可能是什么原因?谢谢
回答 代码应该是这样的
procedure TMainForm.OnWindowsEnd(var Msg: TMessage); // responds to message WM_ENDSESSION;
begin
// Possible checking for flags, see http://msdn.microsoft.com/en-us/library/aa376889%28v=vs.85%29.aspx
AllowClose:=true;
Msg.Result:=1;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose:=AllowClose;
if NOt AllowClose then
Hide;
end;
I have an application that hides itself on closing by the red cross. User can exit it by right-clicking tray icon and choosing Exit. But it would apparently block windows from shutting down, so I made a procedure to respond to a WM_QUERYENDSESSION to enable closing, this is the relevant code:
procedure TMainForm.OnWindowsEnd(var Msg: TMessage); // responds to message WM_QUERYENDSESSION;
begin
AllowClose:=true;
Close;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose:=AllowClose;
if NOt AllowClose then
Hide;
end;
But weird thing keeps happening. When I issue a shutdown, this application closes nicely. But that is all. When I issue a second shutdown, system quits fine. (I'm testing this in WinXP).
What can be the cause? Thank you
ANSWER
Code should look like this
procedure TMainForm.OnWindowsEnd(var Msg: TMessage); // responds to message WM_ENDSESSION;
begin
// Possible checking for flags, see http://msdn.microsoft.com/en-us/library/aa376889%28v=vs.85%29.aspx
AllowClose:=true;
Msg.Result:=1;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose:=AllowClose;
if NOt AllowClose then
Hide;
end;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WM_QUERYENDSESSION
是一个“查询”,而不是关闭命令:Windows 会询问您是否同意关闭,而不是要求您关闭。您不应该调用Close
!其次,Windows 希望您在处理该消息时返回 TRUE,因此它知道您可以接受潜在的关闭。我假设您没有将结果设置为 TRUE,因此 Windows 中止第一个关闭请求。
WM_QUERYENDSESSION
is a "query", not a shutdown command: Windows asks you if you're OK with shutting down, doesn't ask you to shut down. You shouldn't callClose
!Secondly Windows expects you to return TRUE when processing that message, so it knows you're OK with a potential Shut Down. I assume you're not setting the result to something TRUE, so Windows aborts the first Shut Down request.