Delphi 開發ActiveX控制元件(非ActiveForm)
Q:為什麼不採用ActiveForm工程?通過它可以快速開發帶窗體控制元件,建立過程也非常簡單(都不用考慮安全介面問題),很省事!
A:如果要實現的功能用不上視窗,而一個帶視窗的空程式就500多KB,不便於ActiveX的釋出,本實現方法可降到100多KB,CAB打包後只有幾十KB; 好吧,我承認我有點體積控。
2. 在該工程中新建一個 Automation Object物件
填寫類名
3.建一個測試方法(Test)
嚮導會自動生成相關程式碼!
注意:
如果需要釋出到Internet,還需要實現一個IObjectSafety介面,標記指令碼是安全的,執行時才不會被IE阻止。如果想線上安裝ActiveX控制元件還需要數字證書籤名後才可以。
unit AXDemo_u; {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, ActiveX, AXDemo_TLB, StdVcl, Windows; type TAXDemoCtrl = class(TAutoObject, IAXDemoCtrl, IObjectSafety) FObjectSafetyFlags: DWORD; { 實現IObjectSafety 介面用於將控制元件標記為安全,否則IE載入時可能會被阻止!} function GetInterfaceSafetyOptions(const IID: TIID; pdwSupportedOptions, pdwEnabledOptions: PDWORD): HResult; stdcall; function SetInterfaceSafetyOptions(const IID: TIID; dwOptionSetMask, dwEnabledOptions: DWORD): HResult; stdcall; protected procedure Test(const Msg: WideString); safecall; implementation uses ComServ; function TAXDemoCtrl.GetInterfaceSafetyOptions(const IID: TIID; pdwSupportedOptions, pdwEnabledOptions: PDWORD): HResult; var Unk : IUnknown; begin if (pdwSupportedOptions = nil) or (pdwEnabledOptions = nil) then Result := E_POINTER; Result := QueryInterface(IID, Unk); if Result = S_OK then pdwSupportedOptions^ := INTERFACESAFE_FOR_UNTRUSTED_CALLER or INTERFACESAFE_FOR_UNTRUSTED_DATA; pdwEnabledOptions^ := FObjectSafetyFlags and (INTERFACESAFE_FOR_UNTRUSTED_CALLER or INTERFACESAFE_FOR_UNTRUSTED_DATA); pdwSupportedOptions^ := 0; pdwEnabledOptions^ := 0; function TAXDemoCtrl.SetInterfaceSafetyOptions(const IID: TIID; dwOptionSetMask, dwEnabledOptions: DWORD): HResult; var Unk : IUnknown; begin Result := QueryInterface(IID, Unk); if Result <> S_OK then FObjectSafetyFlags := dwEnabledOptions and dwOptionSetMask; procedure TAXDemoCtrl.Test(const Msg: WideString); begin MessageBox(GetActiveWindow, PChar(string(Msg)), initialization TAutoObjectFactory.Create(ComServer, TAXDemoCtrl, Class_AXDemoCtrl, ciMultiInstance, tmApartment);
部署測試:
html> <head> <title>ActiveX Test Page</title> </head> <H1>ActiveX Test Page</H1> <hr> <p> <body> <object classid="clsid:C7C16439-AFF0-48A4-A22D-4655400FC4BE" codebase="AXDemo.cab#version=1,0,0,0"> </object> <script> functiontry'Hello World!'catch'ActiveX測試失敗!\r\n'+</script>