通过对消息函数(SendMessage、PostMessage、Perform)的一般应用,来说明sendmessage、postmessage函数和perform 方法调用方式和结果的区别。
一、程序界面
二、程序代码及注释
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Edit1: TEdit; Button1: TButton; Button2: TButton; Button3: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure MyWMClose(var Amessage: TWMClose); message WM_CLOSE; {拦截关闭窗口消息} end; var Form1: TForm1; implementation uses CommCtrl; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin SendMessage(Edit1.Handle, WM_SETTEXT, 255, Integer(PChar(‘abc‘))); {发送字符ABC} // Edit1.Perform(WM_SETTEXT,255,Integer(PChar(‘abc‘))); // PostMessage(Edit1.Handle,WM_SETTEXT,255,Integer(PChar(‘abc‘))); //SendMessage(Edit1.Handle,WM_Char,Wparam(‘Q‘),1); {传递字符 } end; procedure TForm1.Button2Click(Sender: TObject);var MyBroadCastMsg:cardinal; begin MyBroadCastMsg:=RegeisterWindowsMessage(‘MyBroadCastMsg‘); //向系统注册消息 SendMessage(HWND_BROADCAST,MyBroadCastMsg,0,0); //向系统广播消息。 //PostMessage(Button2.Handle, BM_SETSTYLE, BS_RADIOBUTTON, 1); //改变按钮风格 end; procedure TForm1.Button3Click(Sender: TObject); begin SendMessage(Handle, WM_CLOSE, 0, 0); {点击按钮后 ,弹出MyWMClose函数窗口,点击取消息按后才会显示“欢迎回来”窗口;} //Form1.Perform(WM_CLOSE, 0, 0); //PostMessage(Handle, WM_CLOSE, 0, 0); {点击按钮后 ,马上显示“欢迎回来”窗口,这是三个函数执行流程区别的体现。} ShowMessage(‘欢迎回来‘); end; procedure Tform1.MyWMClose(var Amessage: TWMClose); {拦截关闭窗口消息 } begin case MessageBoxW(Handle, ‘确认关闭窗口?‘, ‘提示‘, MB_OKCANCEL + MB_ICONQUESTION) of IDOK: begin Close; end; IDCANCEL: begin end; end; end; end.
分析:PostMessage函数与SendMessage函数和Perform方法主要区别在执行流程上的区别,PostMessage函数就象甩手雷,只管甩,不管是不是哑弹,可以连续甩。而SendMessage函数和Perform不仅要甩,而且要等到手雷爆炸后才能甩下一个。
原文地址:https://www.cnblogs.com/LifeStartPoint/p/12207030.html
时间: 2024-11-13 11:26:49