首页 > 代码库 > delphi处理消息的几种方式
delphi处理消息的几种方式
第一种:自定义处理单条消息
[delphi] view plaincopy
- 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处理消息
[delphi] view plaincopy
- 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.
第三种:自己处理窗口函数,个人感觉这是最强大的,可以拦截一切发往窗口的消息!
[delphi] view plaincopy
- 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.
delphi处理消息的几种方式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。