问题描述
我的类包含数据集(TDataSet)。我的类的用户可以为此数据集分配事件处理程序: ds.FieldByName('ID')OnChange:= @ID_OnChange ;
然后我必须重新打开数据集:
ds.Close;
ds.Open;
所有事件处理程序都消失了:
if Assigned(ds.FieldByName('ID')。OnChange)//返回false
所以,我需要保存处理程序并重新打开后恢复。我使用TStringList:
var
EventHandlers:TStringList;
...
//我为每个字段的每个事件执行此操作
如果分配(ds.FieldByName('ID')。OnChange)然后
EventHandlers.AddObject(' ID',@ ds.FieldByName('ID')。OnChange);
问题是如何恢复处理程序:
ds.FieldByName('ID')OnChange:= TFieldNotifyEvent(ObjToInt(EventHandlers.Objects [0])); //无效的类型转换错误
如何将存储的地址分配给事件处理程序?
谢谢。
如果您真的要保存事件,可以使用TMethod Record:
单位Unit6; unit Unit6;
接口
使用
Windows,消息,SysUtils,变体,类,图形,控件,窗体,
对话框,StdCtrls;
type
TForm6 = class(TForm)
btn1:TButton;
btn2:TButton;
procedure btn1Click(Sender:TObject);
procedure btn2Click(Sender:TObject);
private
{私有声明}
public
{公开声明}
MTD:TMethod;
结束
var
Form6:TForm6;
实现
{$ R * .dfm}
程序TForm6.btn1Click(发件人:TObject);
begin
ShowMessage('Hello World!');
结束
程序TForm6.btn2Click(发件人:TObject);
begin
ShowMessage('我是复制猫!');
MTD:= TMethod(btn1.OnClick);
btn2.OnClick:= TNotifyEvent(MTD);
结束
结束。
首先点击Btn2将显示我是复制猫!而第二个将显示Hello World。
编辑:改进分配事件到MTD(TMethod)。更简单,并允许来自其他对象的事件。
My class contains dataset (TDataSet). Users of my class can assign event handlers for this dataset:
ds.FieldByName('ID').OnChange := @ID_OnChange;
Then I have to reopen dataset:
ds.Close;
ds.Open;
After this all event handlers are gone:
if Assigned(ds.FieldByName('ID').OnChange) //returns false
So, I need to save handlers and restore them after reopen. I use TStringList for it:
var
EventHandlers: TStringList;
...
//I do this for every event of every field
if Assigned(ds.FieldByName('ID').OnChange) then
EventHandlers.AddObject('ID', @ds.FieldByName('ID').OnChange);
The problem is how to restore handlers:
ds.FieldByName('ID').OnChange := TFieldNotifyEvent(ObjToInt(EventHandlers.Objects[0]));//Invalid typecast error
How can I assign stored address to event handler?Thanks.
If you really want to save the events, you can use TMethod Record:
unit Unit6;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm6 = class(TForm)
btn1: TButton;
btn2: TButton;
procedure btn1Click(Sender: TObject);
procedure btn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
MTD : TMethod;
end;
var
Form6: TForm6;
implementation
{$R *.dfm}
procedure TForm6.btn1Click(Sender: TObject);
begin
ShowMessage('Hello World!');
end;
procedure TForm6.btn2Click(Sender: TObject);
begin
ShowMessage('I am copy cat!');
MTD := TMethod(btn1.OnClick);
btn2.OnClick := TNotifyEvent(MTD);
end;
end.
The First Click on Btn2 will show "I am copy cat!" and The 2nd one will show Hello World.
Edit : Improve assign event to MTD(TMethod). More simple and allow events from other objects.
这篇关于保存并恢复事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!