很多时候自定义或者引用控件都需要注册才能使用,但是如何使要注册的dll或ocx打包到exe中,使用户下载以后看到的只是一个exe,点击直接运行呢?就像很多安全控件,如支付宝的aliedit.exe那样。前面已经发布了C#版控件注册的例子。
现在介绍一下使用资源文件,将dll、ocx打包进exe,点击直接注册的例子:
首先,新建一个工程,在“外接程序”->“外接程序管理器”->“VB 6 资源管理器” 添加资源文件,可以讲图标、image等文件添加进去,这里我们添加的是ocx。添加后保存会生成一个.reg文件,就是我们的资源文件。
接下来,新建一个模块,注册ocx的函数,代码如下:
- '新建一个模块
- Option Explicit
- Private Declare Function GetSystemDirectory Lib "kernel32" Alias _
- "GetSystemDirectoryA" (ByVal lpBuffer As String, _
- ByVal nSize As Long) As Long
- Public Sub RegsvrFile(ByVal ResourceID As Integer, strFormat As String, strFileName As String)
- Dim bytArr() As Byte
- Dim strSystemPath As String
- Dim Filenum As Long
- 'on error resume next
- strSystemPath = String(255, 0)
- GetSystemDirectory strSystemPath, 256
- strSystemPath = Left(strSystemPath, InStr(1, strSystemPath, Chr(0)) - 1)
- bytArr = LoadResData(ResourceID, strFormat)
- Filenum = FreeFile
- Open strSystemPath & "/" & strFileName For Binary As #Filenum
- Put #1, , bytArr
- Close #Filenum
- Call Shell("regsvr32 " + strFileName, vbHide)
- End Sub
最后,在主窗体中调用:
- Option Explicit
- Private Sub Form_Load()
- RegsvrFile 101, "CUSTOM", "dsoframer.ocx"
- RegsvrFile 102, "CUSTOM", "dsoframerctl.ocx"
- Unload Me
- End Sub