第一种:自定义处理单条消息
- unit Unit2;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs;
- type
- TForm2 = class(TForm)
- procedure FormCreate(Sender: TObject);
- procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
- private
- { Private declarations }
- //直接用 TWMQueryEndSession
- procedure EndMsg(var nMsg: TWMQueryEndSession); Message WM_QUERYENDSESSION;
- //也可以用这种
- //procedure EndMsg(var nMsg: TMessage); Message WM_QUERYENDSESSION;
- public
- { Public declarations }
- end;
- var
- Form2: TForm2;
- implementation
- {$R *.dfm}
- //收到WM_QUERYENDSESSION消息后就会触发这个过程
- procedure TForm2.EndMsg(var nMsg: TWMQueryEndSession);
- begin
- //0 可以取消关机操作
- nMsg.Result := 1;
- ShowMessage(‘注销、重启、关机‘);
- end;
- end.
第二种:利用Application.OnMessage处理消息
- unit Unit2;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs;
- type
- TForm2 = class(TForm)
- procedure FormCreate(Sender: TObject);
- private
- { Private declarations }
- public
- { Public declarations }
- procedure OnMsg(var nMsg: tagMSG; var nHandled: Boolean);
- end;
- var
- Form2: TForm2;
- implementation
- {$R *.dfm}
- //消息处理过程
- procedure TForm2.OnMsg(var nMsg: tagMSG; var nHandled: Boolean);
- begin
- //处理……
- //这里会收到各种消息……经测试无法收到WM_QUERYENDSESSION消息
- end;
- procedure TForm2.FormCreate(Sender: TObject);
- begin
- Application.OnMessage := OnMsg;
- end;
- end.
第三种:自己处理窗口函数,个人感觉这是最强大的,可以拦截一切发往窗口的消息!
- unit Unit2;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs;
- type
- TForm2 = class(TForm)
- procedure FormCreate(Sender: TObject);
- private
- { Private declarations }
- public
- { Public declarations }
- procedure WndProc(var nMsg: TMessage); override;
- end;
- var
- Form2: TForm2;
- implementation
- {$R *.dfm}
- procedure TForm2.WndProc(var nMsg: TMessage);
- begin
- //这里能收到发往窗口的所有消息
- inherited; // 注意这句不能少
- if nMsg.Msg = WM_QUERYENDSESSION then
- begin
- if nMsg.LParam = 0 then
- ShowMessage(‘关机或重启‘)
- else
- ShowMessage(‘注销‘);
- end;
- end;
- end.