Delphi 7學習開發控件(繼承TGraphicControl只畫一條線)

      咱們知道使用Delphi快速開發,很大的一方面就是其強大的VCL控件,另外豐富的第三方控件也使得Delphi程序員更加快速的開發出所須要的程序。在此不特別介紹一些概念,只記錄本身學習開發控件的步驟。假設咱們要開發一個畫直線的控件,那麼咱們從下面開始作:
1.菜單欄→Component→New Component,在彈出的對話框中按照提示添加:程序員

Ancestor type 父類:TGraphicControl  [Controls]
Class Name 類名:TLineTo
Palette Page 面板頁:Samples
Unit file name 單元文件名:E:/練習/我作的控件/TLineTo.pas
Search path 搜索路徑:E:/練習/我作的控件 (添加上面保存控件的路徑)ide


按OK完成,系統自動幫咱們建立好LineTo.pas文件,內容以下:函數

unit LineTo; 
 
interface 
 
uses 
  SysUtils, Classes, Controls; 
 
type 
  TLineTo = class(TGraphicControl) 
  private 
    { Private declarations } 
  protected 
    { Protected declarations } 
  public 
    { Public declarations } 
  published 
    { Published declarations } 
  end; 
 
procedure Register; 
 
implementation 
 
procedure Register; 
begin 
  RegisterComponents('Samples', [TLineTo]); 
end; 
 
end. 
 

2.咱們建立的TLineTo派生自TGraphicControl,而TGraphicControl又派生自TControl,那麼圖像控件TGraphicControl源代碼又是什麼呢,Ctrl按住並點擊TGraphicControl,進入觀看源代碼:學習

  TGraphicControl = class(TControl) 
  private 
    FCanvas: TCanvas; 
    procedure WMPaint(var Message: TWMPaint); message WM_PAINT; 
  protected 
    procedure Paint; virtual; 
    property Canvas: TCanvas read FCanvas; 
  public 
    constructor Create(AOwner: TComponent); override; 
    destructor Destroy; override; 
  end; 

能夠看到父類TGraphicControl的Paint是虛函數,子類必須覆蓋實現Paint函數方法。要作畫線控件,咱們簡單來句MoveTo,LineTo就能夠了,源代碼以下:測試

unit LineTo; 
 
interface 
 
uses 
  SysUtils, Classes, Controls; 
 
type 
  TLineTo = class(TGraphicControl) 
  private 
    { Private declarations } 
  protected 
    procedure Paint; override; 
  public 
    { Public declarations } 
  published 
    { Published declarations } 
  end; 
 
procedure Register; 
 
implementation 
 
procedure Register; 
begin 
  RegisterComponents('Samples', [TLineTo]); 
end; 
 
procedure TLineTo.Paint; 
begin 
  with Canvas do 
  begin 
    MoveTo(0, 0); 
    LineTo(Self.Width, Self.Height); 
  end; 
end; 
end. 

保存文件,關閉文件。
3.接下來安裝組件,菜單欄→Component→Install Component,彈出對話框,瀏覽加入剛纔製做的組件全路徑位置,記住第三項包文件名,之後卸載須要使用,點擊「OK」安裝。以下圖所示:設計

彈出確認對話框,點「Yes」繼續安裝。安裝完畢,彈出消息對話框,提示包已經安裝完成,新組件LineTo.TlineTo已經註冊完成。在面板Samples就能夠看到新組件LineTo,以下圖所示:開發

關閉dclusr.dpk文件,彈出對話框,詢問是否保存(Save changes to project dclusr?)按「Yes」安裝完成退出。
4.測試組件,菜單欄→File→New→Application,從Samples面板拖動LineTo控件到窗體上,能夠看到控件上從左上角到右下角畫出了一條直線,設計期和運行後的界面以下圖所示:it

5.默認的控件圖標不具備其所表明的特色,咱們使用Delphi 7下的Image Editor編輯控件圖標,菜單欄→File→New→Component Resource File (.dcr),在Contents上右鍵→New→Bitmap,設置Bitmap屬性,大小爲24x24,VGA(16 colors),而後在生成的Bitmap1上右鍵→Rename,重命名跟控件類名同樣,而且都大寫,爲TLINETO,而後雙擊它,就出現空白位圖對話框,在裏面繪製圖標,以下圖所示:io

而後保存到跟製做的畫線控件同樣的路徑下,名稱爲LineTo.dcr。
6.卸載控件,再從新安裝以測試圖標是否會更新。在菜單欄→File→Open...→dclusr.dpk,在其Contains下選中LineTo.pas,而後點上面的Remove,再選中LineTo,按「ok」,彈出確認移除對話框,單擊」Yes「,再點擊下Compile,那麼面板Samples上的LineTo就消失了。保存dclusr.dpk退出。再從新安裝一遍控件,安裝完成後的圖標以下圖所示:class

製做簡單的畫線控件先到這裏,下次再增強此控件,接着學習

相關文章
相關標籤/搜索