您的位置:首页 > 编程语言 > VB

Create a ActiveX user control (VB.NET2005)

2011-09-13 19:53 459 查看
The problem with that example is that is does not register the control, and the example will only work for putting it in a web page.
I did get this to work. The .Net user control can be hosted in VB6, VBA web forms, but not, I found, all ActiveX containers. Here are the details for those interested in what I did.

1. Create a VB.NEt user control (VB 2005)

2. Put a button on the control

3. Set project property "Register for COM interop"

4. Modify the usercontrol1.vb as show below

BUILD VB.Net user control which will register the ActiveX control

5. In VB6, add control (assembly namespace.MyControl")

Code:

Imports System.Runtime.InteropServices

Imports System.Text

Imports System.IO

Imports System.Reflection

Imports Microsoft.Win32

Imports System

Imports System.Threading

Imports System.Math

<ComClass(MyControl.ClassId, _

MyControl.InterfaceId, _

MyControl.EventsId)> _

Public Class MyControl

' MAKE SURE WE HAVE 1 PUBLIC SUB in this class

#Region "COM GUIDs"

' These GUIDs provide the COM identity for this class

' and its COM interfaces. If you change them, existing

' clients will no longer be able to access the class.

'You should create your own 3 GUIDS using GuidGen

Public Const ClassId As String = "8D6CC4E9-1AE1-4909-94AF-8A4CDC10C466"

Public Const InterfaceId As String = "D901FC53-EEC2-4634-A1B5-BB4E41B24521"

Public Const EventsId As String = "7458968F-F760-4f53-A2E4-30C1D8CD691B"

#End Region

#Region "REQUIRED FOR ACTIVEX"

' This function is called when registered (no need to change it)

<ComRegisterFunction()> _

Private Shared Sub ComRegister(ByVal t As Type)

Dim keyName As String = "CLSID\\" & t.GUID.ToString("B")

Dim key As RegistryKey = Registry.ClassesRoot.OpenSubKey(keyName, True)

key.CreateSubKey("Control").Close()

Dim subkey As RegistryKey = key.CreateSubKey("MiscStatus")

subkey.SetValue("", "131201")

subkey = key.CreateSubKey("TypeLib")

Dim libid As Guid = Marshal.GetTypeLibGuidForAssembly(t.Assembly)

subkey.SetValue("", libid.ToString("B"))

subkey = key.CreateSubKey("Version")

Dim ver As Version = t.Assembly.GetName().Version

Dim version As String = String.Format("{0}.{1}", ver.Major, ver.Minor)

If version = "0.0" Then version = "1.0"

subkey.SetValue("", version)

End Sub

' This is called when unregistering (no need to change it)

<ComUnregisterFunction()> _

Private Shared Sub ComUnregister(ByVal t As Type)

' Delete entire CLSID¥{clsid} subtree

Dim keyName As String = "CLSID\\" & _

t.GUID.ToString("B")

Registry.ClassesRoot.DeleteSubKeyTree(keyName)

End Sub

#End Region

Private Sub UserControl1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

MessageBox.Show("OK")

End Sub

End Class
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: