学习官方示例 - TApplication.OnMessage

本例演示了一个消息的定义、发送和接受的过程.
本例效果图:

学习官方示例 - TApplication.OnMessage
代码文件:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    procedure AppMessage(var Msg: TMsg; var Handled: Boolean);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

const WM_MyMessage = WM_USER + 2000;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Application.OnMessage := AppMessage;
  Button1.Caption := '发送自定义消息';
end;

procedure TForm1.AppMessage(var Msg: TMsg; var Handled: Boolean);
var msgStr: String;
begin
  if Msg.hwnd = Application.Handle then
  begin
    if Msg.message = WM_MyMessage then
    begin
      msgStr:= PChar(Msg.lParam);
      ShowMessage(msgStr);
      Handled := True;
    end;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
const lParam: PChar = '来自定义消息';
begin
  PostMessage(Application.Handle, WM_MyMessage, 0, Integer(lParam));
end;

end.

 
 
 
 
 

 

 
  
窗体文件:
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 117
  ClientWidth = 225
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesktopCenter
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 48
    Top = 48
    Width = 129
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
    OnClick = Button1Click
  end
end

 
 
 
 
 

 

 
  

你可能感兴趣的:(学习官方示例 - TApplication.OnMessage)