定義乙個訊息需要兩個步驟:
1.宣告乙個訊息識別符號
2.宣告乙個訊息記錄型別
tmessage =
packed
record
msg: cardinal;
case integer
of0: (
wparam: longint;
lparam: longint;
result: longint);
1: (
wparamlo: word;
wparamhi: word;
lparamlo: word;
lparamhi: word;
resultlo: word;
resulthi: word);
end;
要宣告乙個訊息記錄型別,請按照下列約定:
1.命名訊息記錄型別,以t開頭
2.第乙個欄位為msg,為對應的訊息
3.定義接下來的兩個位元組對應word引數,接下來的兩個位元組為未使用。
或接下來的四個位元組定義對應於longint型引數。
4.最後字段新增乙個型別為longint型的result。
如delphi原始碼裡面:
twmchartoitem =
packed
record
msg: cardinal;
key: word;
caretpos: word;
listbox: hwnd;
result: longint;
end;
twmcompacting =
packed
record
msg: cardinal;
compactratio: longint;
unused: longint;
result: longint;
end;
有不同的方式來傳送乙個windows訊息,經常使用的是sendmessage和postmessage,它們原型如下:
function sendmessage(hwnd: hwnd; msg: uint; wparam: wparam; lparam: lparam): lresult;
stdcall;
function postmessage(hwnd: hwnd; msg: uint; wparam: wparam; lparam: lparam): bool;
stdcall
其中wparam和lparam都是longint。這兩個函式引數一樣,返回值不同。sendmessage()返回被處理的訊息的結果值,但是postmessage()返回的只是乙個布林值,表示是否該訊息被放入到目標視窗佇列中。另外乙個方面,sendmessage()是同步呼叫的,postmessage()是非同步呼叫的。
下面乙個例子來說明,如何自定義訊息。示例功能為應用程式呼叫計算器類,當計算器類計算完畢,就髮帶計算結果的訊息給應用程式:
1.新建delphi 7應用程式,單擊選單欄→file→new→unit,在彈出的單元檔案,輸入以下**:
unit unit2;
inte***ce
uses
classes, windows, messages;
const
100;
//定義訊息
type
tcalc =
class(tobject)
private
fformhandle: hwnd;
//接受者的控制代碼
fone,fanother: integer;
public
constructor create(ahandle: hwnd;aone,aanother: integer);
procedure startcalc;
end;
implementation
constructor tcalc.create(ahandle: hwnd;aone,aanother: integer);
begin
inherited create;
fformhandle := ahandle;
fone := aone;
fanother := aanother;
end;
procedure tcalc.startcalc;
vars: string;
begin
s :=
'計算結果:';
sendmessage(fformhandle,wm_calcok,fone + fanother,longint(s));
//程序內傳送字串
//postmessage(fformhandle,wm_calcok,fone + fanother,0); //不可傳送字串
end;
end.
unit unit1;
inte***ce
uses
windows, messages, sysutils, variants, classes, graphics, controls, forms,
dialogs, stdctrls, unit2;
const
100;
type
tform1 =
class(tform)
btn1: tbutton;
edt1: tedit;
edt2: tedit;
procedure btn1click(sender: tobject);
private
fcalc: tcalc;
procedure calcok(
var msg: tmessage);
message wm_calcok;
public
end;
varform1: tform1;
implementation
procedure tform1.btn1click(sender: tobject);
begin
fcalc := tcalc.create(self.handle,strtoint(edt1.text),strtoint(edt2.text));
tryfcalc.startcalc;
finally
fcalc.free;
end;
end;
procedure tform1.calcok(
var msg: tmessage);
begin
showmessage(
string(msg.lparam) + inttostr(msg.wparam));
end;
end.
3.執行程式,結果如下所示:
Delphi 7中的四種訊息框
1.showmessage 顯示乙個帶 ok 按鈕的訊息框 使用這個函式可以顯示乙個簡單的帶 ok 按鈕的訊息框,訊息框的標題是應用程式的標題名,引數msg字串顯示在訊息框上。其原始碼如下 procedure showmessage const msg string begin showmessag...
Delphi7的IDE概述 一
ideograph margin 0cm 10.8pt 0pt 13.2pt text align justify mso para margin top 0cm mso para margin right 9gd mso para margin bottom 0001pt mso para mar...
Delphi 7 中DBGrid的排序。
procedure tfrmtracereport.dbgrid1titleclick column tcolumn var sortfield,fieldtitle string begin sortfield column.field.fieldname fieldtitle column.ti...