抛砖引玉:从你用监视的控件继承一个类,比如要监视tbutton类的caption属性,用下面的代码。
新增一个属性mycation 代替 caption,以后就通过访问mycaption 来访问caption.设置
一个OnWriteCaption事件监视caption属性.
unit mybt;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,stdctrls;
type
tmybutton = class(TButton)
private
FOnWriteCaption: TNotifyEvent;
public
procedure writeCaption(value:string);
function readCaption:string;
published
property OnWriteCaption: TNotifyEvent read FOnWriteCaption write FOnWriteCaption;
property MyCaption: string read readCaption write writecaption;
end;
implementation
procedure tmybutton.writeCaption(value:string);
var tmpstr:string;
begin
if value=caption then exit;
caption := value;
if assigned(FOnwriteCaption) then
FOnwriteCaption(self);
end;
function tmybutton.readCaption;
begin
result := caption;
end;
end.
然后在主窗口创建tmybutton的实例:
unit mf;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,mybt;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure button2OnOnWriteCaption(Sender: TObject);
end;
var
Form1: TForm1;
button2:tmybutton;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
button2:=tmybutton.Create(self);
button2.Parent:=self;
button2.OnWriteCaption := button2OnOnWriteCaption;
button2.MyCaption:='aaa';
end;
procedure tform1.button2OnOnWriteCaption(sender: TObject);
begin
showmessage(button2.Caption);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
button2.MyCaption:=button2.MyCaption+'1';
end;
end.
可以看到效果,遗憾的是Caption属性仍然是公有的,但把它设成私有程序就运行不正常了。
不知哪位有更好的办法。