225
陳寬達 (陳存暘) 講師、技術作家、共享軟體作者 Borland C++Builder Borland C++Builder 進階課程 進階課程

Borland C++Builder 進階課程 - pudn.comread.pudn.com/downloads110/ebook/454671/BCB_AdvSlides.pdf · 2008-04-18 · Win32 開發工具的比較 • g µWjtvbm!D,, D,,Cvjmefs! DEfmqij!

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

  • 陳寬達 (陳存暘)

    講師、技術作家、共享軟體作者

    Borland C++BuilderBorland C++Builder進階課程進階課程

  • OutlinesOutlines•

  • Win32 Win32 開發環境開發環境•

  • 獨立的獨立的 44GB GB 位址空間-位址空間-Windows 95/98 Windows 95/98 架構架構

  • 獨立的獨立的 44GB GB 位址空間-位址空間-Windows NT Windows NT 架構架構

  • 多執行緒支援多執行緒支援

  • 何謂行程(何謂行程(processprocess))??

  • 何謂執行緒(何謂執行緒(threadthread))??

  • 多執行緒程式多執行緒程式

  • 多執行緒的優劣多執行緒的優劣

  • Win32 APIWin32 API•

  • Win32 APIWin32 API•

    Project1

    ColorToIdent RTL BitBlt API CreateFile API

    Project1.exe

    function ColorToIdent;begin ... // 實作 ColorToIdent 功能end;

    function BitBlt;begin ... // 實作 BitBlt 功能end;

    GDI32.DLL

    function CreateBitmap;begin ... // 實作 CreateBitmap 功能end;

    function CreateFile;begin ... // 實作 CreateFile 功能end;

    function LoadLibrary;begin ... // 實作 LoadLibrary 功能end;

    KERNEL32.DLL

  • DLL DLL 釋名釋名

  • DLL DLL 的重要性的重要性

  • DLL DLL 的重要性的重要性

  • 檢視檢視 DLL DLL 提供的函式提供的函式E:\WINNT\system32>dumpbin /exports user32.dll

    Microsoft (R) COFF Binary File Dumper Version 5.00.7022Copyright (C) Microsoft Corp 1992-1997. All rights reserved.

    Dump of file user32.dll

    File Type: DLL

    Section contains the following Exports for USER32.dll

    0 characteristics336A2A2A time date stamp Sat May 03 01:53:46 1997

    0.00 version1 ordinal base

    634 number of functions634 number of names

    ordinal hint name

    1 0 ActivateKeyboardLayout (00015B1A)2 1 AdjustWindowRect (0000D704)3 2 AdjustWindowRectEx (00007D8E)4 3 AnyPopup (00043ABB)5 4 AppendMenuA (00011F57)6 5 AppendMenuW (0002D7A4)

  • 檢視檢視 DLL DLL 提供的資源提供的資源

  • DLL DLL 的運作特徵的運作特徵

  • DLL DLL 的載入方式的載入方式

  • 訊息驅動訊息驅動

  • 處處皆訊息處處皆訊息•

  • 視窗訊息結構視窗訊息結構

    typedef struct tagMSG { // 訊息結構HWND hwnd; // 視窗編號UINT message; // 訊息編號WPARAM wParam; // 參數 1LPARAM lParam; // 參數 2DWORD time; // 時間POINT pt; // 滑鼠座標

    } MSG;

  • 訊息的傳遞方式訊息的傳遞方式

    •–

    •–

  • •–

    以程式產生/傳遞訊息以程式產生/傳遞訊息

  • 以程式產生/傳遞訊息以程式產生/傳遞訊息

    void __fastcall TForm1::Button1Click(TObject *Sender){

    HWND wnd;if (wnd = FindWindow(NULL, "小算盤")) {

    PostMessage(wnd, WM_KEYDOWN, '1', 0);PostMessage(wnd, WM_CLOSE, 0, 0);

    };}

    void __fastcall TForm1::Button1Click(TObject *Sender){

    HWND wnd;if (wnd = FindWindow(NULL, "小算盤")) {

    SendMessage(wnd, WM_SETTEXT, 0, (LPARAM)"測試,測試");};

    }

  • 訊息處理機制訊息處理機制

    USER32.DLL

    messages

    send /

    post

    messa

    ges

    post messages

    while (GetMessage(&Msg, NULL, NULL, NULL)){

    TranslateMessage(Msg);DispatchMessage(Msg);

    }

    switch (Msg.Message) {// 視窗建立時case WM_CREATE: ... // 按下滑鼠左鍵case WM_LBUTTONDOWN: ... // 按下按鍵時case WM_KEYDOWN: ... // 關閉視窗時case WM_CLOSE: ...

    }DefWindowProc(..)

  • 行程、執行緒、訊息佇列及行程、執行緒、訊息佇列及訊息迴圈訊息迴圈

  • 行程、執行緒、訊息佇列及行程、執行緒、訊息佇列及訊息迴圈訊息迴圈

  • 開發工具的型態及演進開發工具的型態及演進

  • 開發工具的型態及演進開發工具的型態及演進

  • Win32 Win32 開發工具的比較開發工具的比較•

    比較項目 Visual C++ C++Builder Delphi

    設計公司 Microsoft Borland

    前端語言 C++ C++ Object Pascal

    ApplicationFramework

    MFC VCL

    介面設計方式 傳統(Class Wizard 及手工打造)

    RAD(拖拉點按)

    程式核心 手工打造(有許多程式庫

    及類別可供運用)

    手工打造(有許多元件、程式庫及類別可供運用)

    運作原理 呼叫 Windows API 呼叫 Windows API

  • RAD RAD 無罪,輕鬆有理無罪,輕鬆有理•

  • RAD RAD 無罪,輕鬆有理無罪,輕鬆有理•

  • C++ LanguageC++ Language••••

  • Programming ParadigmProgramming Paradigm

  • Procedural Procedural Programming ParadigmProgramming Paradigm

  • ADT Programming ParadigmADT Programming Paradigm

  • ObjectObject--OrientedOrientedProgramming ParadigmProgramming Paradigm

  • 物件導向程式設計物件導向程式設計

    •••

    ––––

    •–

  • 物件導向要素-封裝物件導向要素-封裝

    •–

  • 物件導向要素-繼承物件導向要素-繼承

  • 物件導向要素-多型物件導向要素-多型

    •–

    •–

  • C++ C++ 的由來的由來

    • “ ”

  • 如何看待如何看待 C++ ?C++ ?•

  • 強大複雜的強大複雜的 C++C++

  • 強大複雜的強大複雜的 C++C++

  • C++ C++ 類別宣告類別宣告

    class TMyClass{

    int a, b, c;

    TMyClass(); // 建構函式~TMyClass(void); // 解構函式

    void draw();int draw(int x, int y, int z);

    };

  • C++ C++ 物件物件••

    void foo(void){

    TCat cat; // 在堆疊中建立 TCat 類別的 cat 物件, 進入 foo 時才建立cat.Meow(); // 呼叫 cat 物件的 Meow() 方法

    }

    TCat cat; // 在資料節區中建立 TCat 類別的 cat 物件, 程式啟動後即建立void foo(void){

    cat.Meow(); // 呼叫 cat 物件的 Meow() 方法}

    void foo(void){

    TButton* btn = new TButton(this); // 在堆疊中建立 TButton 類別的 btn 物件btn->Show(); // 呼叫 btn 物件的 Show() 方法

    }

  • TMammal and child classesTMammal and child classes

    class TMammal{private:

    AnsiString FName, FEyeColor;int FAge;

    public:__fastcall TMammal(void);

    virtual void __fastcall Speak(void) = 0;};

    class TCat : public TMammal{virtual void __fastcall Speak(void) {ShowMessage(“I’m Cat”);}};

    class TDog : public TMammal{virtual void __fastcall Speak(void) {ShowMessage(“I’m Dog”);}};

  • The Power of PolymorphismThe Power of Polymorphism

    void __fastcall TForm1::Button1Click(TObject *Sender){

    TMammal* Mammal = new TCat();Mammal->Speak();delete Mammal;

    }

    void __fastcall TForm1::Button2Click(TObject *Sender){

    TMammal* Mammal = new TDog();Mammal->Speak();delete Mammal;

    }

  • C++ Enhancement for BCBC++ Enhancement for BCB•••

    ••••

  • Added KeywordsAdded Keywords•

    ––

  • PropertiesProperties•

    ––

    •class TMyClass{private:

    TColor FColor;TColor __fastcall GetColor( void );

    public: __fastcall TMyClass( void );__property TColor Color = { read = FColor, write = SetColor };

    };

  • DFM resourcesDFM resources••

    #include #pragma hdrstop

    #include "Unit1.h"//---------------------------------------------------------#pragma resource "*.dfm” //

  • AnsiString Class and VariantAnsiString Class and Variant•

    ––––

    void __fastcall TForm1::Button1Click(TObject *Sender){

    Variant x;

    x = 13;edtTest->Text = IntToStr( x + 12 );x = "Hello, world";ShowMessage( x );

    }

  • SetSet•

    Type the type of the set (usually a char orenum type)

    M inimum Value the smallest value the set can holdM aximum Value the largest value the set can hold

    typedef Set UPPERCASESet;UPPERCASESet s;

  • Open ArrayOpen Array•

    ShowMessage(Format("%s %d", OPENARRAY(TVarRec, ("Hello",

    123))));

  • Traditional Methods for Error Traditional Methods for Error HandlingHandling

    if ((pBuffer = malloc(1000)) == NULL) {/* error processing code here; */

    }

    if ((fp = fopen(“data.txt”, “r”)) == NULL) {/* error processing code here; */

    }

  • Handling VCL ExceptionHandling VCL Exception•

    try{

    edtTotal->Text = IntToStr( StrToInt( edtOp1->Text ) /StrToInt( edtOp2->Text ) );

    }catch ( EDivByZero& ){

    ShowMessage( "Cannot divide by zero" );}catch ( EConvertError& ){

    ShowMessage( "Error during conversion" );}

  • Unhandled VCL ExceptionsUnhandled VCL Exceptions•

    WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int){try{

    Application->Initialize();Application->CreateForm(__classid(TForm1), &Form1);Application->Run();

    }catch (Exception &exception){

    Application->ShowException(&exception);}return 0;}

  • Throwing exceptionsThrowing exceptions•

    try{

    if (numItems == 0 )throw EDivByZero( "Cannot divide by zero" ); // ^ throw your own exception

    elseedtAvg->Text = FloatToStr( sum / numItems );

    }catch ( EDivByZero& ){

    edtAvg->Text = FloatToStr( 0.0 );throw; //

  • Creating Custom Exception Creating Custom Exception ClassClass

    class EInvalidBalance : public Exception{public:

    virtual __fastcall EInvalidBalance( String msg ) :Exception( msg ) {};

    };

  • VCL VCL 的多重面貌的多重面貌

    •–

    •–

  • VCL VCL 的原始碼面貌的原始碼面貌•

  • VCL VCL 的編譯後單元面貌的編譯後單元面貌•

  • VCL VCL 的類別及元件面貌的類別及元件面貌•

  • VCL VCL 的執行檔面貌的執行檔面貌•

    99/11/25 08:09p 16,384 Project1.exe

    99/11/25 08:10p 292,864 Project1.exe

  • VCL VCL 的的 RunTime RunTime Package Package 面貌面貌

  • VCL VCL 的的 RunRun--TimeTimePackage Package 面貌面貌

    99/11/25 08:10p 292,864 Project1.exe

    99/11/25 08:20p 13,824 Project1.exe

  • VCL VCL 的的 RunRun--TimeTimePackage Package 面貌面貌

    ••

  • VCL VCL 的的 RunRun--TimeTimePackage Package 面貌面貌

    P ac k a g e 名 稱 單 元 名 稱

    V C L 5 0 .B P L A x , B u tton s , C la ss es , C lip brd , C om ctrls, C om m ctr l, C om m d lg , C om ob j ,C om s tr s, C on sts , C on tro ls, D d e m l, D ia logs , D lgs , D s gn in tf, D s gn w n d s,E d i tin t f, E x p t in tf, E x tc trls, E x td lgs, F ile in tf, F o rm s, G rap h ics, G r id s, Im m ,In iF i le s, Is a p i , Is a p i2 , Is t re a m s , L ib h elp , L ib in tf, L ze x p a n d , M a p i, M as k ,M ath , M e nu , M e ss a ge s, M m s ys te m , N sa p i, O le 2 I, O le con s t, O le ctn rs ,O le c trls, O led lg , P en w in , P rin te rs, P rox ies , R e g istry, R e gs tr, R ich e d i t,S h e llap i, S h lob j, S td c trls, S td vcl , S ysu tils , T lhe lp3 2 , T oo l in tf, T oo lw in ,T yp in fo , V clcom , V irt in t f, W in d ow s, W in in et , W ins ock , W ins p oo l, W in s vc

    V C L X 5 0 .B P L C h e ck lst , C o lorgrd , D d e m a n , F i le c trl , M pla ye r , O u tl ine , T ab n o tb k , T a bs

    V C L D B 5 0 .B P L B d e , B d e con s t, B d e prov , D b , D b cgr ids , D b clie n t , D b com m on , D b con s ts ,D b ctr ls , D b gr id s, D b inp req , D blogd lg , D b p w dlg , D b tab le s, D s in tf,P rov id e r , S M in tf

    V C L D B X 5 0 .B P L D b look u p , R e p or t

    D S S 5 0 .B P L M x arra ys , M xb u t ton , M x com m on , M x con s ts, M x db , M x d cu b e , M x d ss q ry,M x gra ph , M x gr id , M xp ivsrc , M x qe d com , M x q p arse , M x qrye d t , M xs to re ,M x ta b le s, M x q vb

    Q R P T 5 0 .B P L Q r2 con s t , Q ra b ou t, Q ra lias, Q rctrls , Q rd atasu , Q re xp b ld , Q re x tra , Q rp re v ,Q rp rg res , Q rp rn tr , Q rq red 3 2 , Q u ick rp t

    T E E 5 0 .B P L A rrow ch a , B u b b le ch , C h art , G a n ttch , S e ries , T ee con s t , T ee fu n ci , T ee n g in e,T e e procs , T ee s ha p e

    T E E D B 5 0 .B P L D b ch a r t, Q rte e

    T E E U I5 0 .B P L A re a e d it, A r row e d i, A x is in cr , A x m a x m in , B a re d it, B ru sh d lg , B ub b led i ,C u s te d it, D be d i tch , E d itch a r, F lin ee d i, G a n tte d i, Ie d itch a, P e n d lg , P iee d i t,S h a p ee d i , T ee a b ou t, T e e gal ly, T e e lis b , T e ep re v i, T e ex p or t

    V C L S M P 5 0 .B P L S a m p re g , S m p con s t

  • 學習學習 VCL VCL 類別架構類別架構•

  • 學習學習 VCL VCL 類別架構類別架構•

  • VCL VCL 核心類別核心類別

    •TObject

    TPersistent

    TComponent

    TApplication

    TControl

    類別 父類別 宣告單元 主要貢獻

    TObject 無 System Object Pascal 裡所有類別的始祖

    TPersistent TObject Classes 資料流讀寫能力

    TComponent TPersistent Classes 所有 VCL 元件的始祖

  • VCL VCL 核心類別-核心類別-TObjectTObject•

  • VCL VCL 核心類別-核心類別-TObjectTObject•

  • VCL VCL 核心類別-核心類別-TObjectTObject•

  • VCL VCL 核心類別-核心類別-TObjectTObject•

    void foo(void){

    TCat cat; // 在堆疊中建立 TCat 類別的 cat 物件, 進入 foo 時才建立cat.Meow(); // 呼叫 cat 物件的 Meow() 方法

    }

    TCat cat; // 在資料節區中建立 TCat 類別的 cat 物件, 程式啟動後即建立void foo(void){

    cat.Meow(); // 呼叫 cat 物件的 Meow() 方法}

    void foo(void){

    TButton* btn = new TButton(this); // 在累堆中建立 TButton 類別的 btn 物件btn->Show(); // 呼叫 btn 物件的 Show() 方法delete btn;

    }

  • VCL VCL 核心類別-核心類別-TObjectTObject•

    TCCalendar = class(TCustomGrid)private

    ... procedure WMSize(var Message: TWMSize); message WM_SIZE;

    end;

  • VCL VCL 核心類別-核心類別-TPersistentTPersistent

  • VCL VCL 核心類別-核心類別-TPersistentTPersistent

    TPersistent = class(TObject)protected

    ...procedure AssignTo(Dest: TPersistent); virtual;

    public...procedure Assign(Source: TPersistent); virtual;

    end;

  • VCL VCL 核心類別-核心類別-TPersistentTPersistent•

  • VCL VCL 核心類別-核心類別-TPersistentTPersistent•

    { TPersistent abstract class }

    {$M+}TPersistent = class(TObject)

    ...end;

    {$M-}

  • VCL VCL 核心類別-核心類別-TComponentTComponent•

  • VCL VCL 控制項類別控制項類別• “ ”

    TComponent

    TControl

    TGraphicControl

    TWinControl

    TCustomControl

    TImage

    TCustomPanel

    TCustomEdit TEdit

  • VCL VCL 控制項類別控制項類別•

    類別 父類別 宣告單元 貢獻

    TControl TComponent Controls 所有 VCL 可視元件的始祖

    TWinControl TControl Controls 所有 VCL 視窗元件的始祖

    TGraphicControl TControl Controls 自製圖形元件的始祖

    TCustomControl TWinControl Controls 自製視窗元件的始祖

  • VCL VCL 控制項類別-控制項類別-TControlTControl•

  • VCL VCL 控制項類別-控制項類別-TWinControlTWinControl

  • VCL VCL 控制項類別-控制項類別-TGraphicControlTGraphicControl

  • VCL VCL 控制項類別-控制項類別-TCustomControlTCustomControl

  • VCL VCL 控制項類別分類控制項類別分類•

  • VCL VCL 控制項類別分類控制項類別分類•

    :hwnd -c project1Handle Class WinProc TID Module03071A IME 77E952BA ED 00000000030724 TForm1 00254477 ED 00010100

    050732 TStaticText 011B0FAE ED 00000000050730 TPanel 011B0FBB ED 0001000003072E TButton 011B0FC8 ED 00000000

    030718 TApplication 011B0FEF ED 0100:0000

  • VCL VCL 控制項類別分類控制項類別分類•

    TControl

    TGraphicControl

    TWinControl

    TCustomControl

    TCustomButton TButton

    TCustomStaticText

    TCustomPanel

    TStaticText

    TCustomLabel

    TShape

    TLabel

    TPanel

  • VCL VCL 控制項的擁有關係控制項的擁有關係•

  • VCL VCL 控制項的擁有關係控制項的擁有關係•

    TWinControl ( )

    TControl( )

    WM_PAINT

    若重繪區域包含此 TControl 元件

    請重繪元件 請重繪視窗

  • VCL VCL 程式運作類別程式運作類別•

    TComponent

    TApplication

    TControl

    TGraphicControl

    TWinControl TScrollingWinControl

    TForm

    類別 父類別 宣告單元 貢獻

    TForm TCustomForm Forms 應用程式視窗

    TApplication TComponent Forms 訊息擷取及分派

  • VCL VCL 程式運作類別-程式運作類別-TFormTForm•

  • VCL VCL 程式運作類別-程式運作類別-TApplicationTApplication

  • VCL RAD VCL RAD 支援類別支援類別•

    TObject

    TStream

    TFiler

    TReader

    TWriter

    TParser

    TFileStream

  • VCL RAD VCL RAD 支援類別支援類別

    類別 父類別 宣告單元 貢獻

    TStream TObject Classes 所有資料流類別的始祖

    TFileStream TStream Classes 檔案資料流

    TFiler TObject Classes 具有讀寫元件能力的類別的始祖

    TReader TFiler Classes 將元件由資料流讀出

    TWriter TFiler Classes 將元件寫入資料流

    TParser TObject Classes 將以文字型式表示的元件,轉換成以二進位型式來表示

  • TStreamTStream•

  • TFilerTFiler•

    • “ ”

  • 元件是啥咚咚?元件是啥咚咚?

    •••

    ––

  • 為什麼要自行撰寫元件?為什麼要自行撰寫元件?

    •••• ’•

  • 元件使用者元件使用者

  • 元件發展者元件發展者

  • 自製元件的種類自製元件的種類

    •–

    •–

    •–

    •–

    •–

  • 撰寫元件六大步驟撰寫元件六大步驟

  • 選擇父代類別選擇父代類別

  • 各類型元件的祖先類別各類型元件的祖先類別TComponent

    TControl

    TGraphicControl

    TWinControl

    TCustomControl

    non-windowed 元件...

    自製 windowed 元件...

    TCustomEdit TEdit

    非可視元件...

    可視元件...

    標準 windowed 元件...

    TCustomPanel

  • 加強型元件-加強型元件-TShellAboutLabelTShellAboutLabel

    •••

    ShellExecute(0, “open”, “mailto:[email protected]”, NULL, NULL, SW_SHOWNORMAL);

  • 加強型元件-加強型元件-TFlatEditTFlatEdit

    ••

  • 功能型元件-功能型元件-TWordCountTWordCount

    •••

  • 組合型元件-組合型元件-TSuperListBoxTSuperListBox

    ••

  • 對話盒元件-對話盒元件-TAboutBoxTAboutBox

    •••

  • 另起爐灶可視元件-另起爐灶可視元件-TRulerTRuler

    •••

  • 另起爐灶可視元件-另起爐灶可視元件-TGradientEditTGradientEdit

    •••••

  • Real life samples from the lecturerReal life samples from the lecturer

    …•

  • Sample 1 Sample 1 -- TxColorMemoTxColorMemo•

    ••

  • Sample 1 Sample 1 -- TxColorMemoTxColorMemo•

  • Sample 2 Sample 2 -- TxMarqueeTxMarquee•••

  • Sample 3 Sample 3 -- TxHexEditTxHexEdit•••••

  • Sample 3 Sample 3 -- TxHexEditTxHexEdit•

  • Mechanisms behind RAD Mechanisms behind RAD EnvironmentEnvironment

    •–

    •–

    •–

  • • ’ “ ”–

    •–

    •–

    Run Time Type InformationRun Time Type Information

  • Run Time Type Run Time Type InformationInformation

    •–

    •–

  • Where is Where is RTTIRTTI ??

    •–

  • Unfold the RTTI Unfold the RTTI DataData of of ObjectsObjects

    Pointer

    Instance VariableP: TMyObject Instance Data

    VMT Pointer

    ...

    Data field 1Data field 2Data field 3

    Virtual Method Table...

    -64-60-56

    04

    -4

    ...Self Pointer

    Type InfoField Table

    DestroyFirst Virtual Method

    ...

    Init Table

    -76

    PTypeInfo = ^TTypeInfo;TTypeInfo = record

    Kind: TTypeKind;Name: ShortString;{TypeData: TTypeData}end;

    Class function TObject.ClassInfo: Pointer;

  • WhatWhat’’s s InsideInside the TTypeInfo the TTypeInfo StructureStructure

    ––––

  • The Advantages RTTI Take to The Advantages RTTI Take to ProgrammersProgrammers

    •–

  • Use Use is And as Operatoris And as Operator

    procedure TForm1.BtnTypeCastClick(Sender: TObject);begin

    if Sender is TMenuItem thenShowMessage(‘Menu: ’ + TMenuItem(Sender).Caption)

    else ShowMessage(‘Button: ’ + (Sender as TButton).Caption);

    end;

  • Know Know MoreMore ThanThan JustJust Name Of Name Of Properties and EventsProperties and Events

    procedure TForm1.Button2Click(Sender: TObject);var

    I : Integer;PropInfo: PPropInfo;

    beginfor I := 0 to ComponentCount - 1 dobegin

    PropInfo := GetPropInfo(Components[I].ClassInfo, 'Color');if PropInfo nil then

    SetOrdProp(Components[I], PropInfo, clRed);end;

    end;

  • Know More Than Just Name of Know More Than Just Name of Properties and EventsProperties and Events

    function IsDataAware(AComponent: TComponent): Boolean;var

    PropInfo: PPropInfo;begin

    // 檢查元件 AComponent 是否擁有 DataSource 屬性PropInfo := GetPropInfo(AComponent.ClassInfo, 'DataSource');Result := PropInfo nil;

    // 謹慎起見,檢查看看那個叫做 DataSource 屬性的型態是否為 TDataSource 或// 其衍生類別if Result thenif not ((PropInfo^.Proptype^.Kind = tkClass) and (GetTypeData(PropInfo^.PropType^).ClassType.InheritsFrom(TDataSource))) then

    Result := False;end;

  • Examine Examine TypeType InfoInfo with RTTIwith RTTI

  • RTTI on Daily BasisRTTI on Daily Basis•

    •–

  • StreamingStreaming•

    •–

  • StreamingStreaming•

  • Streaming ElementsStreaming Elements

    • ’

  • Streaming Streaming MechanismMechanism

    own

    writeTWriter DFM file

    component

    TStream

    create

    WriteComponentRes functionTStream.WriteComponentTStream.WriteComponentResTStream.WriteDescentTStream.WriteDescentRes

    componentcomponentcomponentcomponent

    own

    componentcomponentcomponentcomponent Delphi RAD IDE /Programmer

    write

  • MultiMulti--Appearance of Appearance of FormsFormsobject Form1: TForm1

    Left = 341

    Top = 337

    Width = 148

    Height = 179

    Caption = 'Form1'

    ...

    object Button1: TButton

    Left = 32

    Top = 16

    ...

    end

    object Button2: TButton

    Left = 32

    Top = 56

    ...

    end

    object Button3: TButton

    Left = 32

    Top = 96

    ...

    end

    end

    = =

  • What What WeWe CanCan DoDo in in StreamingStreamingProcess ?Process ?

    •–

  • Additional Data in StreamAdditional Data in Streamobject Form1: TForm1...object Timer1: TTimerLeft = 264Top = 176

    endobject Memo1: TMemo...Lines.Strings = ('Memo1''Line 2''Line 3')

    endobject StatusBar1: TStatusBar...Panels = <itemWidth = 50

    enditemBevel = pbRaisedWidth = 50

    enditemWidth = 50

    end>end

    end

  • procedure TComponent.DefineProperties(Filer: TFiler);var

    Ancestor: TComponent;Info: Longint;

    beginInfo := 0;Ancestor := TComponent(Filer.Ancestor);if Ancestor nil then Info :=

    Ancestor.FDesignInfo;Filer.DefineProperty('Left', ReadLeft,

    WriteLeft,LongRec(FDesignInfo).Lo LongRec(Info).Lo);

    Filer.DefineProperty('Top', ReadTop, WriteTop,LongRec(FDesignInfo).Hi LongRec(Info).Hi);

    end;

    Overrided Overrided TComponent.DefinePropertiesTComponent.DefineProperties

    procedure TComponent.ReadLeft(Reader: TReader);

    beginLongRec(FDesignInfo).Lo := Reader.ReadInteger;

    end;

    procedure TComponent.ReadTop(Reader: TReader);

    beginLongRec(FDesignInfo).Hi := Reader.ReadInteger;

    end;

    procedure TComponent.WriteLeft(Writer: TWriter);

    beginWriter.WriteInteger(LongRec(FDesignInfo).Lo);

    end;

    procedure TComponent.WriteTop(Writer: TWriter);

    beginWriter.WriteInteger(LongRec(FDesignInfo).Hi);

    end;

  • Overrided Overrided TStrings.DefinePropertiesTStrings.DefineProperties

    procedure TStrings.ReadData(Reader: TReader);

    beginReader.ReadListBegin;BeginUpdate;

    tryClear;

    while not Reader.EndOfList do Add(Reader.ReadString);

    finally

    EndUpdate;end;

    Reader.ReadListEnd;end;

    procedure TStrings.WriteData(Writer: TWriter);var

    I: Integer;begin

    Writer.WriteListBegin;for I := 0 to Count - 1 do

    Writer.WriteString(Get(I));Writer.WriteListEnd;

    end;

    procedure TStrings.DefineProperties(Filer: TFiler);

    function DoWrite: Boolean;begin

    if Filer.Ancestor nil thenbegin

    Result := True;if Filer.Ancestor is TStrings then

    Result := not Equals(TStrings(Filer.Ancestor))

    endelse Result := Count > 0;

    end;

    beginFiler.DefineProperty('Strings', ReadData,

    WriteData, DoWrite);end;

  • Streaming on Daily BasisStreaming on Daily Basis

    •– ’– ’

  • Other Other TopicsTopics on on StreamingStreaming

    •–––––

    •–TComponent = class(TPersistent)published

    property Name: TComponentName read FName write SetName stored False;property Tag: Longint read FTag write FTag default 0;

    end;

  • MessagingMessaging

    • ’

  • MessagingMessaging

    USER32.DLL

    Message Loop(TApplication.ProcessMessage)

    ...TObjectInstance

    TObjectInstanceTObjectInstance

    TObjectInstance

    TObjectInstanceTObjectInstance

    WndProc

    Dispatch

    message method 1message method 2message method 3...

    DefaultHandler

    DefWindowProc

    window

    Forms.StdWndProc

    MainWndProc

    messages

    post messages

    send / post messages

    TWinControl

  • Opportunities of Opportunities of InterceptingInterceptingMessagesMessages

    •–

    TDog = class(TWinControl)private

    procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;

    end;

  • Other Other TopicsTopics on on WindowWindow and and MessagingMessaging

    •–

    •–

  • SummarySummary

    •–

  • 多執行緒支援多執行緒支援

    • Process–

    – event

    – device context

    • thread–

    – CPU

  • 何謂行程(何謂行程(processprocess))??• .EXE)

    •– 4GB

    – event semaphores...

  • 何謂執行緒(何謂執行緒(threadthread))??

  • 多執行緒程式多執行緒程式

  • 多執行緒的優劣多執行緒的優劣

    •–

    – polling interrupt / event-driven

    – (multi-processors)

    •–

  • 執行緒的分類執行緒的分類

  • 使用使用 VCL VCL 的執行緒類別的執行緒類別

    •–

  • 使用使用 TThread TThread 類別注意事項類別注意事項

  • 最簡單的最簡單的 TThread TThread 後代類別後代類別__fastcall TSleepThread::TSleepThread(bool CreateSuspended): TThread(CreateSuspended){

    FreeOnTerminate = true;}

    void __fastcall TSleepThread::Execute(){

    Sleep(10 * 1000);}

    void __fastcall TForm1::Button3Click(TObject *Sender){

    TSleepThread* trd = new TSleepThread(true);trd->OnTerminate = SleepThreadFinish;trd->Resume();

    }

    void __fastcall TForm1::SleepThreadFinish(TObject *Sender){

    ShowMessage("Finish");}

  • 透過透過 Synchronize Synchronize 方法方法來使用來使用 VCL VCL 物件物件

    void __fastcall TCalcThread::Execute(){

    for (int i = 0; i < 100 && !Terminated; i++) {...

    FStep++;Synchronize(UpdateProgressBar);

    }}

    void __fastcall TCalcThread::UpdateProgressBar(void){

    Form1->ProgressBar1->Position = FStep;}

  • 多執行緒隱含的陷阱-多執行緒隱含的陷阱-以以 TTimer TTimer 元件為例元件為例

    TForm1.Button1Click;begin // 建立執行緒 with TTimerThread.Create do OnTerminate := ThreadTerminate;end;

    TForm1.ThreadTerminate;begin // 執行緒結束前會執行end;

    主執行緒

    UNIT1.PAS

    UNIT2.PASTTimerThread.Create;begin ... FTimer := TTimer.Create;end;

    TApplication.ProcessMessage;begin // 訊息迴圈 if Message = WM_TIMER then ...// 計時器觸發end;

    TTimerThread.TimerOnTimer;begin ... // 計時器觸發end;

    工作執行緒

    TForm1.Button1Click;begin TTimerThread.Create; // 建立執行緒end;

    UNIT1.PAS

    UNIT2.PASTTimerThread.Destroy;begin FTimer.Free; // 摧毀 Timer

    DoTerminate; // 觸發 OnTerminate 事件 ...end;

    TTimerThread.Execute;begin ... // 執行緒方法end;

    TTimerThread.Synchronize;begin ... // 透過主執行緒執行某方法end;

    TTimerThread.DoTerminate;begin // 主執行緒執行 OnTerminate 事件處理方法 Synchronize(Terminate);end;

  • 多執行緒隱含的陷阱-多執行緒隱含的陷阱-以以 TTimer TTimer 元件為例元件為例

  • SummarySummary

    •–

  • DLL DLL 釋名釋名

    • DLL stands for Dynamic Linked Library.

    • Dynamic static – Dynamic (late-binding)

    – Static (early-binding)

    • Linked DLL DLL

    • Library DLL

  • DLL DLL 的重要性的重要性

    • Win32 DLL

    • Win32 API DLL

    • COM ActiveX DLL

    • DLL

  • DLL DLL 的重要性的重要性

    • console mode DLL

  • 檢視檢視 DLL DLL 提供的函式提供的函式E:\WINNT\system32>dumpbin /exports user32.dll

    Microsoft (R) COFF Binary File Dumper Version 5.00.7022Copyright (C) Microsoft Corp 1992-1997. All rights reserved.

    Dump of file user32.dll

    File Type: DLL

    Section contains the following Exports for USER32.dll

    0 characteristics336A2A2A time date stamp Sat May 03 01:53:46 1997

    0.00 version1 ordinal base

    634 number of functions634 number of names

    ordinal hint name

    1 0 ActivateKeyboardLayout (00015B1A)2 1 AdjustWindowRect (0000D704)3 2 AdjustWindowRectEx (00007D8E)4 3 AnyPopup (00043ABB)5 4 AppendMenuA (00011F57)6 5 AppendMenuW (0002D7A4)

  • 檢視檢視 DLL DLL 提供的資源提供的資源

  • DLL DLL 的運作特徵的運作特徵

    • DLL

    • DLL reference count

    DLL

    • DLL

  • DLL DLL 的載入方式的載入方式

    • Implicitly linked–

    – implicitly linked DLLs

    – implicitly linked DLLs

    • Explicitly linked–

    – LoadLibrary API DLLGetProcAddress DLL

  • 撰寫撰寫 DLL DLL 的大致步驟的大致步驟

  • DLL DLL 函式的宣告方式函式的宣告方式

    extern "C" {void _stdcall ShowAboutBox(void);

    }

    void _export _stdcall ShowAboutBox(void){

    ...}

    extern "C" {__declspec(dllimport) int _stdcall AddInteger(int, int);

    }

    __declspec(dllimport) int _stdcall AddInteger(int a,int b){

    return a + b;}

  • DLL DLL 函式的宣告方式函式的宣告方式

    #ifndef XXXDLL#define EXTERN __declspec(dllimport) // 用於應用程式#else#define EXTERN __declspec(dllexport) // 用於 DLL#endif

    extern "C" {EXTERN int _stdcall AddInteger(int, int);

    }

    EXTERN int _stdcall AddInteger(int a,int b){

    return a + b;}

  • DLL DLL 函式的使用方式-函式的使用方式-Implicitly LinkingImplicitly Linking

    d:\BCB\lecture>IMPLIB XXXDLL.LIB XXXDLL.DLL

    Borland Implib Version 3.0.8 Copyright (c) 1991, 1999 Inprise Corporation

    #include

  • DLL DLL 函式的使用方式-函式的使用方式-Explicitly LinkingExplicitly Linking

    int _stdcall (*AddInteger)(int, int);

    ShowMessage(IntToStr(AddInteger(2, 3)));

    HINSTANCE hInst;hInst = LoadLibrary(”e:\\dll\\xxxdll.dll");

    (FARPROC&)AddInteger = GetProcAddress(hInst, "AddInteger");

    FreeLibrary(hInst);

  • 資源檔建立方式資源檔建立方式

    Garf BITMAP garf200.bmp

    STRINGTABLE {100, "Oh Oh, I am resource string"}

    d:\bcb\lecture>brcc32 xxxdll.rcBorland Resource Compiler Version 5.40Copyright (c) 1990, 1999 Inprise Corporation. All rights reserved.

  • DLL DLL 資源宣告方式資源宣告方式

    #pragma resource "calcdll.res"

  • DLL DLL 資源使用方式資源使用方式•

    •–

    Image1->Picture->Bitmap->LoadFromResourceName((int)hInst,"Garf");

    HINSTANCE hInst;hInst = LoadLibrary(”e:\\dll\\xxxdll.dll");

    char buf[256];

    LoadString(hInst, 100, buf, sizeof(buf));ShowMessage(buf);

  • SummarySummary

    • “ ”

  • 1

    COMCOM

    Component Object ModelComponent Object Model

  • 2

    OutlinesOutlines

  • 3

    Why COM ?Why COM ?• “ ”

  • 4

    ComponentComponent•

    Comp A

    Comp B

    Comp C

    Com

    p D

    Com

    p E

    Comp A

    Comp B

    Comp C

    Com

    p D

    New

    versionof C

    omp E

  • 5

    Advantages of Using ComponentAdvantages of Using Component•

    Proxy of Comp A

    Comp B

    Proxy of Comp C

    Comp A

    networkComp C

  • 6

    Object Model RequirementsObject Model Requirements•

    – –

  • 7

    COM SpecificationCOM Specification•

  • 8

    COM IS NOT ...COM IS NOT ...•

  • 9

    InterfaceInterface•

    – “ ”

  • 10

    Interface (cont)Interface (cont)•

  • 11

    QueryInterfaceQueryInterface• –

  • 12

    Reference CountingReference Counting•

  • 13

    Class and Interface NamingClass and Interface Naming•

    • “ ”

    “ ”

  • 14

    Techniques based on COMTechniques based on COM•

  • 15

    ConclusionsConclusions•

  • 善用除錯工具,縮短開發時間善用除錯工具,縮短開發時間

  • 資源保固機制資源保固機制

    GetMem(p, 100);try

    ... // 儘情使用 pfinally

    FreeMem(p);end;

    try... Exit; // 離開此 procedure 或 function

    finally... // 善後工作

    end;

  • 例外處理機制例外處理機制

    GetMem(pBuffer, 1000);if (pBuffer = nil) thenbegin/* error processing code here; */

    end;

    // 取得 x, 計算 x 的倒數if x = 0 thenbegin/* error processing code here; */

    end;

  • 例外處理機制例外處理機制

    tryedtTotal.Text := IntToStr( StrToInt( edtOp1.Text ) /

    StrToInt( edtOp2.Text ) );

    excepton EDivByZero do ShowMessage('Cannot divide by zero');

    on EConvertError do ShowMessage('Error during conversion');end;

  • 例外處理機制例外處理機制

    tryif numItems = 0 thenraise EDivByZero.Create('Cannot divide by zero')// ^ throw your own exception

    elseedtAvg.Text := FloatToStr( sum / numItems );

    exceptedtAvg.Text := FloatToStr(0.0);raise; //

  • 例外處理機制例外處理機制

    EInvalidBalance = class(Exception);

    raise EInvalidBalance.Create('Invalid Number');

  • 例外處理機制例外處理機制

  • Assert Assert 程序程序

    procedure TForm1.SetID(Id: Integer);begin

    Assert((id) >= ID_MIN and (id

  • Assert Assert 程序程序

    •void __fastcall TForm1::SetID(int id){

    char *p = malloc(100);assert(p != NULL);

    ...};

  • OutputDebugString OutputDebugString 除錯字串除錯字串

  • OutputDebugString OutputDebugString 除錯字串除錯字串

  • 系統層級除錯器-系統層級除錯器-SoftICESoftICE

  • 系統層級除錯器-系統層級除錯器-SoftICESoftICE•

  • 系統層級除錯器-系統層級除錯器-SoftICESoftICE

  • 系統層級除錯器-系統層級除錯器-SoftICESoftICE

  • SummarySummary

  • 實作與理論實作與理論

    …•

    …•

  • 實作與理論實作與理論

  • 實作與理論實作與理論•

  • 實作與理論實作與理論• 模擬

  • 參考書目參考書目 --C / C / C++ ProgrammingC++ Programming

  • 參考書目-參考書目-Delphi / C++BuilderDelphi / C++Builder

  • 參考書目參考書目 --Windows ProgrammingWindows Programming

    • ’

  • 參考書目-參考書目-OOA / OOD / OOPOOA / OOD / OOP

  • 參考書目-參考書目-Practical Programming Practical Programming

  • 參考書目-參考書目-工具書工具書

  • Delphi Delphi 深度歷險深度歷險

  • Delphi Delphi 深度論壇深度論壇

  • Delphi Delphi 深度歷險深度歷險

  • THE ENDTHE END

    進階_開場.pdfOutlinesWin32 開發環境獨立的 4GB 位址空間-�Windows 95/98 架構獨立的 4GB 位址空間-�Windows NT 架構多執行緒支援何謂行程(process)?何謂執行緒(thread)?多執行緒程式多執行緒的優劣Win32 APIWin32 APIDLL 釋名DLL 的重要性DLL 的重要性檢視 DLL 提供的函式檢視 DLL 提供的資源DLL 的運作特徵DLL 的載入方式訊息驅動處處皆訊息視窗訊息結構訊息的傳遞方式以程式產生/傳遞訊息以程式產生/傳遞訊息訊息處理機制行程、執行緒、訊息佇列及�訊息迴圈行程、執行緒、訊息佇列及�訊息迴圈開發工具的型態及演進開發工具的型態及演進Win32 開發工具的比較RAD 無罪,輕鬆有理RAD 無罪,輕鬆有理

    語言.pdfC++ LanguageProgramming ParadigmProcedural �Programming ParadigmADT Programming ParadigmObject-Oriented� Programming Paradigm物件導向程式設計物件導向要素-封裝物件導向要素-繼承物件導向要素-多型C++ 的由來如何看待 C++ ?強大複雜的 C++強大複雜的 C++C++ 類別宣告C++ 物件TMammal and child classesThe Power of PolymorphismC++ Enhancement for BCBAdded KeywordsPropertiesDFM resourcesAnsiString Class and VariantSetOpen ArrayTraditional Methods for Error HandlingHandling VCL ExceptionUnhandled VCL ExceptionsThrowing exceptionsCreating Custom Exception Class

    VCL.pdfVCL 的多重面貌VCL 的原始碼面貌VCL 的編譯後單元面貌VCL 的類別及元件面貌VCL 的執行檔面貌VCL 的 RunTime �Package 面貌VCL 的 Run-Time�Package 面貌VCL 的 Run-Time�Package 面貌VCL 的 Run-Time�Package 面貌學習 VCL 類別架構學習 VCL 類別架構VCL 核心類別VCL 核心類別-TObjectVCL 核心類別-TObjectVCL 核心類別-TObjectVCL 核心類別-TObjectVCL 核心類別-TObjectVCL 核心類別-TPersistentVCL 核心類別-TPersistentVCL 核心類別-TPersistentVCL 核心類別-TPersistentVCL 核心類別-TComponentVCL 控制項類別VCL 控制項類別VCL 控制項類別-TControlVCL 控制項類別-TWinControlVCL 控制項類別-TGraphicControlVCL 控制項類別-TCustomControlVCL 控制項類別分類VCL 控制項類別分類VCL 控制項類別分類VCL 控制項的擁有關係VCL 控制項的擁有關係VCL 程式運作類別VCL 程式運作類別-TFormVCL 程式運作類別-TApplicationVCL RAD 支援類別VCL RAD 支援類別TStreamTFiler

    進階_元件.pdf元件是啥咚咚?為什麼要自行撰寫元件?元件使用者元件發展者自製元件的種類撰寫元件六大步驟選擇父代類別各類型元件的祖先類別加強型元件-�TShellAboutLabel加強型元件-�TFlatEdit功能型元件-�TWordCount組合型元件-�TSuperListBox對話盒元件-TAboutBox另起爐灶可視元件-TRuler另起爐灶可視元件-TGradientEditReal life samples from the lecturerSample 1 - TxColorMemoSample 1 - TxColorMemoSample 2 - TxMarqueeSample 3 - TxHexEditSample 3 - TxHexEdit

    進階_RAD.pdfMechanisms behind RAD EnvironmentRun Time Type InformationRun Time Type InformationWhere is RTTI ?Unfold the RTTI Data of ObjectsWhat’s Inside the TTypeInfo StructureThe Advantages RTTI Take to ProgrammersUse is And as OperatorKnow More Than Just Name Of Properties and EventsKnow More Than Just Name of Properties and EventsExamine Type Info with RTTIRTTI on Daily BasisStreamingStreamingStreaming ElementsStreaming MechanismMulti-Appearance of FormsWhat We Can Do in Streaming Process ?Additional Data in StreamOverrided TComponent.DefinePropertiesOverrided TStrings.DefinePropertiesStreaming on Daily BasisOther Topics on StreamingMessagingMessagingOpportunities of Intercepting MessagesOther Topics on Window and MessagingSummary

    進階_執行緒.pdf多執行緒支援何謂行程(process)?何謂執行緒(thread)?多執行緒程式多執行緒的優劣執行緒的分類使用 VCL 的執行緒類別使用 TThread 類別注意事項最簡單的 TThread 後代類別透過 Synchronize 方法�來使用 VCL 物件多執行緒隱含的陷阱-�以 TTimer 元件為例多執行緒隱含的陷阱-�以 TTimer 元件為例Summary

    進階_DLL.pdfDLL 釋名DLL 的重要性DLL 的重要性檢視 DLL 提供的函式檢視 DLL 提供的資源DLL 的運作特徵DLL 的載入方式撰寫 DLL 的大致步驟DLL 函式的宣告方式DLL 函式的宣告方式DLL 函式的使用方式-Implicitly LinkingDLL 函式的使用方式-Explicitly Linking資源檔建立方式DLL 資源宣告方式DLL 資源使用方式Summary

    COM.pdfOutlinesWhy COM ?ComponentAdvantages of Using ComponentObject Model RequirementsCOM SpecificationCOM IS NOT ...InterfaceInterface (cont)QueryInterfaceReference CountingClass and Interface NamingTechniques based on COMConclusions

    除錯.pdf善用除錯工具,縮短開發時間資源保固機制例外處理機制例外處理機制例外處理機制例外處理機制例外處理機制Assert 程序Assert 程序OutputDebugString 除錯字串OutputDebugString 除錯字串系統層級除錯器-SoftICE系統層級除錯器-SoftICE系統層級除錯器-SoftICE系統層級除錯器-SoftICESummary

    進階_結語.pdf實作與理論實作與理論實作與理論實作與理論參考書目 - �C / C++ Programming參考書目- �Delphi / C++Builder參考書目 - �Windows Programming參考書目- �OOA / OOD / OOP參考書目- �Practical Programming 參考書目- �工具書Delphi 深度歷險Delphi 深度論壇Delphi 深度歷險THE END