Delphi控件开发浅入深出(七)

来源:互联网 发布:淘宝宝贝怎么排名靠前 编辑:程序博客网 时间:2024/06/04 17:54

对话框控件的制作

Delphi中有很多对话框组件,例如TopenDialogTfontDialog等。这些控件的特点就是虽然是不可视控件,但是在运行时都有一个可视化的效果,比如TopenDialog的可视化效果就是一个打开对话框。我们这次将开发一个日期对话框控件,当我们调用控件的Execute方法(不一定非要使用Execute方法,不过大部分对话框控件都是使用这个方法,我们也就按照惯例来了)时,就会弹出一个可以选择日期的对话框,我们选择一个日期后,点击“确定”则Execute返回True,点击“取消”则Execute返回False。我们可以读取Date属性来得到用户选择的日期,也可以修改此属性来改变对话框的初始日期。

1、新建一个对话框。在对话框窗体上放置一个TmonthCalendar组件,命名为Cal,窗体名称改为FormDate。在窗体上放置两个按钮,一个按钮的Caption为“确定(&O)”,ModalResultmrOk,一个按钮的Caption为“取消(&C)”,ModalResultmrCancel。设计好的窗体如下图所示:

delphicomdev7-1.jpg

2、为窗体添加两个Public访问级的方法:

    function GetSelDate: TDate;

    procedure SetInitDate(AValue: TDate);

代码如下:

function TFormDate.GetSelDate: TDate;

begin

  result := cal.Date;

end;

 

procedure TFormDate.SetInitDate(AValue: TDate);

begin

  cal.Date := AValue;

end;

3、新建一个控件,派生自Tcomponent

代码如下:

unit DateDialog;

 

interface

 

uses

  SysUtils, Classes, Controls, frmDlg;

 

type

  TDateDialog = class(TComponent)

  private

    FDlg: TFormDate;

    function GetDate: TDate;

    procedure SetDate(AValue: TDate);

  protected

  public

    constructor Create(AOwner: TComponent);override;

    function Execute: Boolean;

  published

    property Date: TDate read GetDate write SetDate;

  end;

 

procedure Register;

 

implementation

procedure Register;

begin

  RegisterComponents('Linco', [TDateDialog]);

end;

constructor TDateDialog.Create(AOwner: TComponent);

begin

  inherited Create(AOwner);

  FDlg := TFormDate.Create(self);

end;

 

function TDateDialog.Execute: Boolean;

begin

  result := (FDlg.ShowModal = mrOK);

end;

 

function TDateDialog.GetDate: TDate;

begin

  result := FDlg.GetSelDate;

end;

 

procedure TDateDialog.SetDate(AValue: TDate);

begin

  FDlg.SetInitDate(AValue);

end;

end.

代码比较简单就不多解释了。

思考题:

1、做一个模仿TcolorDialog的对话框控件。

 
原创粉丝点击