【发布时间】:2016-09-05 09:01:20
【问题描述】:
我正在尝试为我们的系统制作一个小型工具,以防止在我们的软件运行时关闭 Windows。为了使其独立,我制作了一个单独的应用程序,使用this 信息防止关机。
但是,当应用程序最小化到托盘时,Windows 会简单地将其杀死并正常关闭。如果表单是可见的(也就是我从 Form.OnCreate 事件中评论 Application.Minimize 调用),它确实可以防止关机。
如何实现 MainWindow 挂钩以保持活动状态,或者通过其他方式防止系统关闭,并将应用程序隐藏在托盘中?
谢谢。
当前代码:
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, TlHelp32, dateutils, Vcl.AppEvnts, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
TrayIcon1: TTrayIcon;
ApplicationEvents1: TApplicationEvents;
procedure FormCreate(Sender: TObject);
function HookEndSession(var Message: TMessage): Boolean;
procedure WMQueryEndSession(var Msg : TWMQueryEndSession) ;
message WM_QueryEndSession;
procedure ApplicationEvents1Minimize(Sender: TObject);
procedure ApplicationEvents1Restore(Sender: TObject);
procedure TrayIcon1DblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var Form1: TForm1;
var Mutex : THandle;
implementation
{$R *.dfm}
procedure TForm1.WMQueryEndSession(var Msg: TWMQueryEndSession);
begin
Msg.Result := 0;
end;
function TForm1.HookEndSession(var Message: TMessage): Boolean;
begin
result := false;
if Message.Msg = WM_ENDSESSION then begin
Message.Result := 0;
result := true;
end;
end;
procedure TForm1.TrayIcon1DblClick(Sender: TObject);
begin
WindowState := wsNormal;
Application.Terminate;
end;
procedure TForm1.ApplicationEvents1Minimize(Sender: TObject);
begin
Hide();
WindowState := wsMinimized;
TrayIcon1.Visible := True;
end;
procedure TForm1.ApplicationEvents1Restore(Sender: TObject);
begin
Application.Minimize;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Mutex := CreateMutex(nil, True, 'preventWinShutdown');
if (Mutex = 0) OR (GetLastError = ERROR_ALREADY_EXISTS) then
Application.Terminate;
Application.HookMainWindow(HookEndSession);
TrayIcon1.Hint := 'Windows Shutdown prevented.';
//Application.Minimize;
end;
end.
【问题讨论】:
标签: delphi delphi-xe3