Windows 以訊息為核心:使用者輸入、系統事件、應用程式間通訊皆封裝為訊息 (MSG 結構) 投遞至執行緒訊息佇列。應用程式主迴圈 (GetMessage/TranslateMessage/DispatchMessage) 依序取出並分派給對應視窗程序 (WndProc)。
TApplication 內建訊息迴圈,提供 OnMessage 事件攔截所有訊息。TControl 引入 WindowProc 屬性指向虛擬方法 WndProc。TObject,內建 Dispatch 方法依 message 指令動態查找對應處理方法。
type
TMessage = packed record
Msg: Cardinal;
case Integer of
0: (WParam: Longint; LParam: Longint; Result: Longint);
1: (WParamLo, WParamHi, LParamLo, LParamHi, ResultLo, ResultHi: Word);
end;
const MY_MSG = WM_USER + 100;
type
TMyMsg = record Msg: Cardinal; Param: Integer; Result: Longint; end;
TMyControl = class(TCustomControl)
protected
procedure HandleMyMsg(var Msg: TMyMsg); message MY_MSG;
end;
procedure TMyControl.HandleMyMsg(var Msg: TMyMsg);
begin
// 處理邏輯
inherited; // 呼叫祖先同訊息處理 (若有)
end;
type TMyComp = class(TGraphicControl)
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
| 成員 | 用途 |
|---|---|
| DefaultHandler(var Msg) | 提供預設處理,可重載攔截所有未處理訊息 |
| Dispatch(var Msg) | 核心分派器,依 message 指令查找方法 |
| WindowProc 屬性 | 可動態替換視窗程序 (子類別化) |
| Perform(Msg, WParam, LParam) | 直接送訊息給自身控件 (同步) |
| Broadcast(var Msg) | 廣播訊息給所有子控件 |
GetMessage / PeekMessage:取訊息。TranslateMessage:虛擬鍵轉字元訊息。DispatchMessage:分派至 WndProc。PostMessage / SendMessage:非同步/同步發送訊息。WndProc 或掛 message 方法。WM_USER + n 避免衝突。inherited;若想保留預設行為則呼叫 inherited 或 DefaultHandler。PostMessage / TThread.Synchronize / TThread.Queue。