读书人

怎么给类 指定事件

发布时间: 2012-03-01 10:25:46 作者: rapoo

如何给类 指定事件
RT。想自己写个简单的 D3D UI。提高下自己。

于是写了个一个类,在设置事件时出现问题了。

type
TXui=class
private
FonMousedown:Tmouseevent;
......
public property OnMouseDown: TMouseEvent read FOnMouseDown write FOnMouseDown;


但是必须像正常的VCL那样使用,可是我想在DLL里面调用这个类。

如果这样使用:
procedure Mousedown1(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
.....
end;
ui:Txui.create......

ui.onmousedown:=Mousedown1;

IDE报错 Incompatible types: 'method pointer and regular procedure'

因为DLL里使用没有窗体。
不能用
procedure Tform1.Mousedown1(Sender: TObject;Button: TMouseButton; Shift: TShiftState; X, Y: Integer);

那么应该怎么给这个类指定事件呢,达到:
使用
ui:=Txui.create;
ui.OnMousedown=Mousedown1;

然后在 MOusedown1 处理 鼠标按下。

[解决办法]
最简的方法,你可以将Mousedown1定义在你的Txui类中,例子:
type
TXui=class
private
FonMousedown:Tmouseevent;
public property OnMouseDown: TMouseEvent read FOnMouseDown write FOnMouseDown;
public
procedure Mousedown1(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);

end;


procedure TXui.Mousedown1(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
end;

var
ui:Txui;
begin
ui:=Txui.Create ;
ui.onmousedown:=ui.Mousedown1;

end.

[解决办法]
不知道你最终需要干什么,是想为控件加入鼠标响应的能力,还是仅仅作一个响应鼠标动作的功能类的接口,如果是后者,那么,你的程序在对类中的事件属性赋值的时是错误的,编译器也提示你了:类型不匹配。
你看看 TMouseEvent 的声明
TMouseEvent = procedure(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer) of object;

其后面有一个 of object
这表示这个 TMouseEvent 是一个类中的方法,也就是说,类型为 TMouseEvent 的变量,只能接受类中的方法为其赋值。所以,你上面声明的
procedure Mousedown1(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
.....
end;
然后将其赋值给
ui.onmousedown:=ui.Mousedown1;
这是错误的。
你可以把
procedure Mousedown1(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);

这个声明移入到你的Form中去声明。然后实现他,然后将其赋值给ui.onmousedown

读书人网 >.NET

热点推荐