Delphi中编写自定义组件

来源:互联网 发布:最新淘宝小号注册机 编辑:程序博客网 时间:2024/04/29 15:16
Delphi提供了丰富的VCL组件供编程人员使用,同时还允许编程人员根据实际需要进行自定义组件的编写。
组件的代码编写和我们平常写的类很相似,但也有几点不同,一个是需要从TComponent类继承而来,另一个是要使用Published关键字定义我们想要出现在对象观察器中的属性是事件,再一个就是我们要把这些代码添加到一个设计包中,之后通过对这个包进行编译和安装来发布我们编写的组件。
组件中事件的定义和属性定义一样,使用Property关键字,事件的类型可以使用Delphi标准的事件类型如TNofifyEvent,或者是自已定义一个事件类型,其定义方式如下:
Type
    TComponentEvent 
= procedure(Params) of object;
其中Params是根据组件需要定义的一个或多个参数,可以是任何类型的。
 
下面我们就以具体的实例来讲解如何在Delphi中编写自定义组件。首先在Delphi中新建一个包,然后在包中添加一个单元文件,在单元文件中定义如下组件类
Type
 TMyComponentEvent 
= procedure (Sender: TObject) of object;
 
 TMyComponent 
= class(TComponent)
 
private
    FMyProperty: String;
    FMyEvent: TMyComponentEvent;
    procedure SetMyProperty(
const Value: String);
 
protected
    ....
 
public
    constructor Create; 
    destructor Destroy; 
override;
    ...
 published
    
//The following propety and event will appear in Object Inspector
    property MyProperty: String read FMyProperty write SetMyProperty;
    property MyEvent: TMyComponentEvent read FMyEvent write FMyEvent;
 end;
实现部分的代码就省略了,此处仅为说明组件的定义。到此就完成了一个组件的定义。接下来我们就需要将这个组件注册到Delphi中,让其他编程人员可以像使用Delphi标准组件一样在组件面板上看到我们定义的组件,并将其拖放到设计窗体上。注册组件我们需要写一个注册过程,Delphi规定这个过程名必须为Register,且没有任何参数,在这个过程中我们只需要调用在Classes单元中定义好的RegisterComponents方法(此方法需要两个参数,第一个是组件面板的名称,第二个就是要注册的组件类数组),就可以将我们写的组定注册到Delphi中并在组件面板中出现。
 
procedure Register;
begin
 RegisterComponents(‘PageName’, [TMyComponent]);
end;
 
编译并安装包,之后就可以在组件面板上看到我们定义的组件图标了。我们发现组件图标使用的是Delphi默认的,不形象,也不个性,我们应该如何为这个组件指定一个个性的图标呢?其实也不难,这里就要用到了Delphi自带的工具Image Editor。
我们打开Image Editor,点击New->Component Resource File,创建一个组件资源文件。此时会出现一个窗体,仅有一个“Components”结点,我们右击该节点,在弹出的上下文菜单中选择“New->Bitmap”,此时“Components”结点下会出现一个Bitmap结点,这个结点下还有一个名为“Bitmap1”的结点,即我们新建的Bitmap对象,将“Bitmap1”结点名称改为我们编写的组件名称,注意这里要全部使用大写。然后双击这个结点就可以编辑一个32×32的图像了。编辑好之后保存这个资源文件,这里又有一点要注意,就是这个资源文件需要和组件注册方法(Register方法)所在的单元文件名相同。最后将这个资源文件加入到我们创建的包中,再重新编译并安装这个包。
 
完整的代码如下:
unit MyComponentUnit;
 
interface
 
uses
 SysUtils, Classes;
 
Type
 TMyComponentEvent 
= procedure (Sender: TObject) of object;
 
 TMyComponent 
= class(TComponent)
 
private
    FMyProperty: String;
    FMyEvent: TMyComponentEvent;
    procedure SetMyProperty(
const Value: String);
 
protected
    ....
 
public
    constructor Create; 
    destructor Destroy; 
override;
    ...
 published
    
//The following propety and event will appear in Object Inspector
    property MyProperty: String read FMyProperty write SetMyProperty;
    property MyEvent: TMyComponentEvent read FMyEvent write FMyEvent;
 end;
 
procedure Register;
 
implementation
 
{ TMyComponent }
 
constructor TMyComponent.Create;
begin
 inherited;
 
end;
 
destructor TMyComponent.Destroy;
begin
 
 inherited;
end;
 
procedure TMyComponent.SetMyProperty(
const Value: String);
begin
 FMyProperty :
= Value;
end;
 
procedure Register;
begin
 RegisterComponents(‘PageName’, [TMyComponent]);
end;
 
end.