Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Secure BlackBox 8
 Resources  
Close
 Our Network  
Close
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:
Total page views :  20355
Total downloads :  265
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
GridViewInCom.zip
 
Become a Sponsor

 

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.


Login to add your contents and source code to 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.