首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

ActiveX 控制項註冊與部署的三種標準方法

     編輯:VC 教學

背景

ActiveX 控制項 (.ocx) 本質是 COM 伺服器 DLL,必須在系統註冊表寫入 CLSID、ProgID、TypeLib、InprocServer32 等鍵值,容器 (VB、VC、BCB、IE、Office) 才能發現並載入。

方法一:RegSvr32.exe (手動/腳本)

rem 註冊
regsvr32.exe "C:\Path\MyControl.ocx"

rem 解除註冊
regsvr32.exe /u "C:\Path\MyControl.ocx"

rem 靜默模式 (無訊息框,適合安裝腳本)
regsvr32.exe /s "C:\Path\MyControl.ocx"
  • 系統內建 (%windir%\System32\regsvr32.exe / SysWOW64\regsvr32.exe for 32-bit on 64-bit)。
  • 原理:載入 DLL → 呼叫 DllRegisterServer / DllUnregisterServer 導出函數。
  • 適用:開發測試、簡單部署、登入腳本。

方法二:安裝程式自動註冊 (InstallShield / Inno Setup / NSIS / WiX)

InstallShield 專業版

  1. 建立元件 → 加入 .ocx 檔案。
  2. 設定元件屬性 Self-Register = Yes (或 .NET COM Interop 選項)。
  3. 建置安裝包,執行安裝時自動呼叫 DllRegisterServer;解除安裝自動呼叫 DllUnregisterServer。

Inno Setup 腳本範例

[Files]
Source: "MyControl.ocx"; DestDir: "{sys}"; Flags: regserver uninsrestartdelete
; regserver = 安裝時註冊 (呼叫 DllRegisterServer)
; uninsrestartdelete = 解除安裝時解除註冊後刪除檔案 (需重啟)

NSIS 腳本範例

Section "ActiveX Control"
  SetOutPath "$SYSDIR"
  File "MyControl.ocx"
  RegDLL "$SYSDIR\MyControl.ocx"  ; 註冊
SectionEnd

Section -Uninstall
  ExecWait '"$SYSDIR\regsvr32.exe" /u /s "$SYSDIR\MyControl.ocx"'
SectionEnd
  • 優點:使用者無感、解除安裝自動清理、支援版本檢查、數位簽章、UAC 提權。
  • 缺點:需學習安裝工具語法。

方法三:程式碼動態註冊 (應用程式啟動時自檢)

// C++ (Windows API)
bool RegisterActiveX(const char* ocxPath) {
    HMODULE h = LoadLibrary(ocxPath);
    if (!h) return false;
    typedef HRESULT (__stdcall *PFN_DLLREG)();
    PFN_DLLREG pfn = (PFN_DLLREG)GetProcAddress(h, "DllRegisterServer");
    if (!pfn) { FreeLibrary(h); return false; }
    HRESULT hr = pfn();
    FreeLibrary(h);
    return SUCCEEDED(hr);
}

// 使用範例 (啟動時)
if (!IsActiveXRegistered("MyControl.ocx")) {
    if (RegisterActiveX(GetSysDir() + "\\MyControl.ocx"))
        MessageBox("ActiveX 元件已自動註冊,請重新啟動程式。");
}
  • 適用:綠色軟體、無安裝程式、需在受限環境 (無管理員權限) 註冊到 HKCU\Software\Classes\CLSID (需控制項支援 Per-User 註冊)。
  • 注意:寫入 HKLM 需管理員權限,Vista+ 需 UAC 提權。

64-bit 系統特別注意

  • 32-bit ActiveX (.ocx) 必須用 32-bit regsvr32 (%windir%\SysWOW64\regsvr32.exe) 註冊,寫入 HKLM\Software\Wow6432Node\Classes\CLSID。
  • 64-bit 容器 (64-bit IE、Office) 只能載入 64-bit ActiveX。
  • 安裝程式需區分目標平台產生對應安裝包。

驗證註冊是否成功

  • regsvr32 /s /n /i:MyControl.ocx (僅驗證,不修改)。
  • 檢查註冊表:HKEY_CLASSES_ROOT\CLSID\{...}、HKEY_CLASSES_ROOT\MyControl.ProgID。
  • 用 OLEVIEW (Windows SDK 工具) 瀏覽類別資訊。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved