This article describes how to sink managed events from Component Object Model (COM) clients (unmanaged code) when you write .NET Windows controls. For example, you sink managed events from COM clients when you run script in Microsoft Internet Explorer.
For information about how to write and how to use managed types from COM, refer to the following Microsoft .NET Framework Developer's Guide documentation:
back to the top
Complete Sample Code Listing
Imports System
Imports System.ComponentModel
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Public Delegate Sub ClickEventHandler(ByVal x As Integer, ByVal y As Integer)
' Source interface for events to be exposed.
' Add GuidAttribute to the source interface to supply an explicit System.Guid.
' Add InterfaceTypeAttribute to indicate that the interface is an IDispatch interface.
<GuidAttribute("1F98211C-7A71-4588-8D4A-AD85CA80BAE7"), _
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)> _
Public Interface ControlEvents
' Add DisIdAttribute to any members in the source interface to specify the COM DISPID.
<DispIdAttribute(1)> _
Sub ClickEvent(ByVal x As Integer, ByVal y As Integer)
End Interface
' Add a ComSourceInterfaces attribute to the control to identify the list of interfaces that are exposed as COM event sources.
<ComSourceInterfaces(GetType(ControlEvents)), _
ClassInterface(ClassInterfaceType.None)> _
Public Class MyVBControl
Inherits System.Windows.Forms.UserControl
Dim tx As New System.Windows.Forms.TextBox()
Public Event ClickEvent(ByVal x As Integer, ByVal y As Integer)
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
Me.Name = "MyVBControl"
initMyVBWindowControl()
'Add any initialization after the InitializeComponent() call.
End Sub
' UserControl overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
' Required by the Windows Form Designer.
Private components As System.ComponentModel.IContainer
' NOTE: The following procedure is required by the Windows Form
' Designer. You can modify it by using the Windows Form Designer.
' Do not modify it by using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
'
' MyVBControl
'
End Sub
Private Sub initMyVBWindowControl()
Size = New System.Drawing.Size(300, 50)
tx.Text = "Click on the TextBox to invoke 'ClickEvent'"
tx.Size = Me.Size
AddHandler tx.Click, New System.EventHandler(AddressOf ClickHandler)
Me.Controls.Add(tx)
End Sub
Private Sub ClickHandler(ByVal sender As Object, ByVal e As System.EventArgs)
RaiseEvent ClickEvent(0, 0)
End Sub
#End Region
End Class