有時候程序在運行當中,不允許別的程序或人為的關閉計算機,除非應用程序知道windows將要退出,其實這樣很簡單,我們都知道系統將要關閉時,會向每一個程序發送WM_QUERYENDSESSION這條關機消息,只要我們的程序接受到此消息后,做恰當的處理即刻完成我們所需要的。
處理windows消息有好幾種,在這里我們利用Application的OnMessage事件,建立響應該事件的過程即可!如下面的例子: unit unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type TForm1 = class(TForm) private { Private declarations } public procedure AppMessageHandler(var Msg:TMsg; var Handled:Boolean);//聲明系統處理消息過程,響應Application的OnMessage事件的過程必須為TMessageEvent類型; { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.AppMessageHandler(var Msg:TMsg; var Handled:Boolean); begin if Msg.message=WM_QueryEndSession then//如果收到的消息為關閉計算機的消息時,進行特別處理,因為只是一個例子,我只寫出彈出對話框,大家可以根據自己程序的需要進行響應的處理; begin if messagedlg('shutdown?',mtconfirmation,mbyesnocancel,0)= mryes then Handled:=true else Handled:=false; end; end; end. 最后在程序的DPR文件中,創建窗體之后但在調用Application.Run前加入 Application.OnMessage:=Form1.AppMessageHandler;即可!
|