Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » VB.NET » Using your C# Components in Visual Basic through COM

Using your C# Components in Visual Basic through COM

Those of you who may have thought that the .NET environment wouldn't allow you to create Components for Visual Basic or Visual C++ or Delphi, Guess again! Microsoft has created several attributes and utilities to make it easy to place a .NET component into the clutches of good old COM. In this article I'll discuss how you can take an existing component and make it accessible in VBA.

Author Rank :
Page Views : 23983
Downloads : 302
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
GridViewInCom.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

 

Fig 1.1 - Output from VBA application accessing the GridViewControl.

Those of you who may have thought that the .NET environment wouldn't allow you to create Components for Visual Basic or Visual C++ or Delphi, Guess again!  Microsoft has created several attributes and utilities to make it easy to place a .NET component into the clutches of good old COM.   In this article I'll discuss how you can take an existing component and make it accessible in VBA.  (The same code could of course apply to VB).

In my previous article on this site, I showed you how you could create a simple gridview control using the listview component.  Now we are going to add a few attributes to some of the code to give the GridView  accessibility from COM in a predictable way.  Below are a few of these attributes and a description of each:

COM Attribute

Description

[GuidAttribute(guid)]

Used to assign a guid to a class or interface. Use GuidGen.exe to generate the guid

[DispId(dispatch id)]

Assigns a dispatch id to a property, field or method in the class for access through the IDispatch interface; could be any integer value

[ProgId(progid)]

The Program Id of the class or interface

[ComRegisterFunction]

Tells the RegAsm.exe utility to call a method of the component while registering the Component. It's placed above the method in the class you wish to execute.

You can use each of these attributes in the grid view to set you up for creating accessibility through COM.

Below are a few lines showing how the attributes are used. 

namespace GridViewSample
{
using System;using System.Collections;

using
System.Core;
using
System.ComponentModel;
using
System.Drawing;
using
System.Data;
using
System.WinForms;
using System.Runtime.InteropServices;
// necessary library to use COM attributes.
///
<summary>
///
Summary description for GridView.
///
</summary>
///
[GuidAttribute("14547C64-EE88-4e4f-BE81-CBB7AB6BB8C6")]

public
class
GridView : System.WinForms.UserControl
{
///
<summary>
///
Required designer variable.
///
</summary>
private
System.ComponentModel.Container components;
private
System.WinForms.ListView listView1;
......

Listing 1 - Using the GuidAttribute to expose a class to COM

In the listing above, the GuidAttribute is used to expose the class.  Note that it can also be used to expose an interface.  I used the Guid generator (guidgen.exe)  utility that ships with most visual studio applications to generate the guid and pasted it from the clipboard into our GuidAttribute.  This  generates a unique guid for our component.  Its also worthy to point out that you  need to include:  using System.Runtime.InteropServices in order to utilize the COM attributes.

Below I use the Dispatch Id attribute over the method SetColumnName to assign it a dispatch id of 1:

[DispId(1)]

public void SetColumnName(int index, string aName)
{
if
(index >= listView1.Columns.Count)
{
MessageBox.Show("SetColumnName:Column out of range");
return;
// precondition
}
listView1.Columns[index].Text = aName;
}

Listing 2 - Using the DispId Attribute to expose class methods to COM.

The only other code requirement for exposing your COM component is that you must have a default constructor(constructor with no arguments) so that COM can create an instance of the object.  Note that the default constructor of the GridView exhibits no change from the previous article, but nevertheless, it needs to be there:

public GridView()
{
// This call is required by the WinForms Form Designer.
InitializeComponent();
InitializeGrid();
// TODO: Add any initialization after the InitForm call.
}

Listing 3 - Default Constructor necessary for COM to access the component.

After you compile your project, you're not finished with the COM exposure process just yet! There are two utilities that ship with the sdk that you need to use to make your assembly accessible through COM.  One is the Type Library Exporting Utility (tlbexp.exe)  and The Register Assembly Utility (regasm.exe).  Both these utilities should already be in your path and can be run from the command prompt.  The command line for tlbexp.exe is shown below.  It's best to run it in the directory of the compiled component to produce a tlb file in that directory:

tlbexp.exe GridViewControl.dll 

This will produce the type library GridViewControl.tlb.

You can actually produce a type library and register it all in one go using the regasm.exe utility as shown below:

RegAsm GridViewControl.dll /tlb:GridViewControl.tlb 

Now you would think you are ready to use your control as a COM component and well.. you can.  The only thing is that with they way Microsoft structured COM components with the new security model, if your component is not a strongly named assembly, it can not be used unless it is placed in the same directory as the application that is using it (such as VB or a VBA application such as Excel).  A strongly named assembly can be accessed from anywhere if it has a key and is signed, and all of this other stuff that I didn't have time to  research for this article. (I was able to gather that you need to use utilities makecert.exe, al.exe, and sn.exe  to get this to happen and somehow get them to work in a shared assembly cache.)  The command sn -v GridViewControl.dll kindly tells me that I don't have a strongly named assembly, so I copied the control into the local directory with my VBA application.

To access the control, I use the name of the namespace containing the class(GridViewControl)  followed by the name of the class(GridView). This string is better known as ProgID and is automatically generated by the regasm.exe utility into the registry and the type library.  Below is the VBA code that utilizes the grid control and outputs it to the screen.  You can test this out with any VBA application as long as you place the GridViewControl.dll in the local directory with the application and register it using regasm.exe as shown above:

Sub DisplayGridView()
' Declare the variable for the GridViewControl
' Remember to reference in in the Tools menu
Dim gc As GridViewControl.GridView
'Create the GridView Com Object
Set gc = CreateObject("GridViewControl.GridView")
' Set up the properties and the size
gc.Visible = True
gc.Enabled = True
gc.TopLevel = True
gc.Text = "My COM Example"
gc.SetBounds(10, 10, 400, 200)
' set the column names
gc.SetColumnName(0, "ID")
gc.SetColumnName(1, "First Name")
gc.SetColumnName(2, "Last Name")
' set the column widths
gc.SetColumnWidth(0, 10)
gc.SetColumnWidth(1, 20)
gc.SetColumnWidth(2, 20)
' set the contents of the cells
gc.SetCell(0, 0, "1")
gc.SetCell(0, 1, "Mike")
gc.SetCell(0, 2, "Gold")
gc.SetCell(1, 0, "2")
gc.SetCell(1, 1, "Bob")
gc.SetCell(1, 2, "Hope")
gc.SetCell(2, 0, "3")
gc.SetCell(2, 1, "John")
gc.SetCell(2, 2, "Doe")
End Sub

One nice thing worth noting, is that the regasm utility automatically generates interfaces for the base class members of the GridView, so you can use methods like SetBounds and properties like Visible to adjust the GridView.  I found some properties did not work, though, because there was no equivalent types in COM that mapped properly even though they were still exposed in the type library.  This may either be a deficiency in Beta 1, or something I was doing wrong :-). Anyway it seems to work well enough for testing purposes. I couldn't quite figure out how to embed the control in the UserForm in VBA, but the control does seem to come up stand alone.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mike Gold

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems.

He can be reached at mike@c-sharpcorner.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Mindcracker MVP Summit 2012
Become a Sponsor
 Comments
Accessing VB.NEt user control in VB form via VC++ type library by Vidya On March 6, 2010

Hello Mike,
We have a VB application that hosts VB.Net (framework 2.0) user controls via VC++ 6.0 type libraries. In the VB.Net user control we have a data grid view with text box, combo box and check box.
When hosted to VB form via VC++ type libraries, we are not able to edit the text box.
(there are other problems too, like combo drop down appears in some ohter place of the form, check box gets checked only sometimes etc.)
The same dot net user control works fine when hosted onto VB directly, without using these VC++ type libraries.

The following is the interface of the type library
[
  uuid (9EF896B1-AB19-11d3-9A8E-0050DA3393D8),
  version (1.0),
  dual,
  nonextensible,
  oleautomation
]
interface ICustomControl : IDispatch {
    // Property: CallBack
    [ helpstring("Set/get a reference to the control's CallBack object, through which it will send events.")]
    [propget]    HRESULT CallBack([out, retval] ICallBack** );
    [propputref] HRESULT CallBack([in] ICallBack* icbPipe);

    // Property: hWnd
    [ helpstring("Returns the control's window handle.")]
    [propget]   HRESULT hWnd([out, retval] long* );

    // Property: Visible
    [helpstring("Show/hide control.")]
    [propget]   HRESULT Visible([out, retval] VARIANT_BOOL* );
    [propput]   HRESULT Visible([in] VARIANT_BOOL );

    // Property: Locked
    [ helpstring("Enable/disable data editing. Setting locked will set the control in a  \"read-only\" mode.")]
    [propget]   HRESULT Locked([out, retval] VARIANT_BOOL* );
    [propput]   HRESULT Locked([in] VARIANT_BOOL fLock);

   
    // Function: Initialize
    [ helpstring("Initialize user control with data to be shown.") ]
    HRESULT Initialize([in] VARIANT vInData);
   
    // Function: Refresh
    [ helpstring("Force repaint of control.")]  
    HRESULT Refresh();

    // Function: SetFocus
    [ helpstring("Set focus in control.")]
    HRESULT SetFocus();
}

The above interface is implemented in dot net user control (because VB is expecting this)

The following is the user control code.

Imports System.Runtime.InteropServices
Imports ABCTypeLib
Imports System.Windows.Forms
Imports System.Drawing
Imports Microsoft.VisualBasic.Compatibility

Public Class ucCustomSetup
    Inherits System.Windows.Forms.UserControl
    Implements AnsurTypeLib.ICustomControl
    <DllImport("user32.dll")> _
    Private Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
    End Function
    Dim intAdded As Integer
    Private _objCallBack As ICallBack
    Private _objConfigData As IConfigData
    Private mfInitializing As Boolean
    Private _testId As Long
    Private _character As String
    Private cmbWorkflow As ComboBox
    Private dtbShortlist As DataTable
    Public WithEvents cmbFunctionArea As System.Windows.Forms.ComboBox

  ''-------------------------------------------------------------------------------
    ' Function : SendChangeEvent
    ' Synopsis:  Sends a change event to ansur.
    '-------------------------------------------------------------------------------
    Private Sub SendChangeEvent()
        On Error Resume Next
        If Not (mfInitializing Or (_objCallBack Is Nothing)) Then
            _objCallBack.SendEvent(AnsurTypeLib.CallBackConstants.CALLBACK_CHANGE)
        End If
    End Sub

    Public Property CallBack() As AnsurTypeLib.ICallBack Implements AnsurTypeLib.ICustomControl.CallBack
        Get
            CallBack = _objCallBack
        End Get
        Set(ByVal value As AnsurTypeLib.ICallBack)
            _objCallBack = value
        End Set
    End Property

    Public ReadOnly Property hWnd() As Integer Implements AnsurTypeLib.ICustomControl.hWnd
        Get
            'hWnd = MyBase.Handle.ToInt32()
            hWnd = MyBase.Handle.ToString()

        End Get
    End Property

    Public Sub Initialize(ByVal vInData As Object) Implements AnsurTypeLib.ICustomControl.Initialize
        mfInitializing = True
        PopulateGrid()
    End Sub

    Public Property Locked() As Boolean Implements AnsurTypeLib.ICustomControl.Locked
        Get
            Return False
        End Get
        Set(ByVal value As Boolean)
            DataGridView1.ReadOnly = value
        End Set
    End Property

    Public Sub Refresh1() Implements AnsurTypeLib.ICustomControl.Refresh
        MyBase.Refresh()
    End Sub

    Public Sub SetFocus() Implements AnsurTypeLib.ICustomControl.SetFocus
        DataGridView1.Focus()
    End Sub

    Public Property Visible1() As Boolean Implements AnsurTypeLib.ICustomControl.Visible
        Get
            Visible1 = MyBase.Visible
        End Get
        Set(ByVal value As Boolean)
            MyBase.Visible = value
        End Set
    End Property

    Private Sub ucCustomSetup_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        Dim X, dx As Single
        Dim Y, dy As Single
        'Resize unit page.
        AxXHelpText1.SetBounds(VB6.TwipsToPixelsX(X), VB6.TwipsToPixelsY(Y + dy), VB6.TwipsToPixelsX(dx), VB6.TwipsToPixelsY(0))
    End Sub

    Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        SendChangeEvent()
    End Sub

    Private Sub DataGrid1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles DataGrid1.KeyPress, DataGridView1.KeyPress
        SendChangeEvent()

    End Sub

    Private Sub DataGrid1_Navigate(ByVal sender As System.Object, ByVal ne As System.Windows.Forms.NavigateEventArgs) Handles DataGrid1.Navigate

    End Sub

    Private Sub DataGridView1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseClick
        SendChangeEvent()
    End Sub
End Class

Please help us.

- Vidya

Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.