Click here to Skip to main content
15,888,527 members
Articles / Programming Languages / C#
Article

Exposing Windows Forms Controls as ActiveX controls

Rate me:
Please Sign up or sign in to vote.
4.86/5 (33 votes)
27 Aug 20014 min read 784.1K   9.4K   180   159
This article describes how to build a Windows Forms control in C# and expose it as an ActiveX control

Introduction

This article will describe how to utilise Windows Forms controls outside of .NET. In a recent MSDN magazine article on .NET Interop available here, various ways of exposing .NET objects to 'legacy' environments are discussed, including the exposure of Windows Forms controls as ActiveX controls.

The problem is that the goalposts have moved since the article was written as Beta 2 is now available, and unfortunately this support has been removed - see this posting on the .NET list at http://discuss.develop.com.

The following image shows a control, written purely within .NET, hosted within an ActiveX control container - in this instance tstcon32.exe.

Image 1

As Beta1 supported this facility, and being somewhat inquisitive, I decided to see if I could find a way to expose controls anyway. The attached project creates the 'Prisoner' control, which won't set the world on fire but does show the main things you need to do in order to get a .NET control up & running within VB6.

CAVEAT: As this support has been dropped from Beta2 of .NET, don't blame me if it fries your PC or toasts the cat.

Now that's out of the way, how's it done?.

Writing the control

  1. Create a new control project from within Visual Studio - my examples are all in C# but VB.NET could also be used.

  2. Add controls etc to the form, put in the code etc.

  3. Add in the following using clauses...

    C#
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Reflection;
    using Microsoft.Win32;
  4. Attribute your class so that it gets a ProgID. This isn't strictly necessary as one will be generated, but it's almost always best to be explicit.
    C#
    [ProgId("Prisoner.PrisonerControl")]
    [ClassInterface(ClassInterfaceType.AutoDual)]

    This assigns the ProgID, and also defines that the interface exposed should be 'AutoDual' - this crufts up a default interface for you from all public, non-static members of the class. If this isn't what you want, use one of the other options.

  5. Update the project properties so that your assembly is registered for COM interop.

    Image 2

    If you're using VB.NET, you also need a strong named assembly. Curiously in C# you don't - and it seems to be a feature of the environment rather than a feature of the compiler or CLR.

  6. Add the following two methods into your class.

    C#
    [ComRegisterFunction()]
    public static void RegisterClass ( string key )
    { 
      // Strip off HKEY_CLASSES_ROOT\ from the passed key as I don't need it
      StringBuilder sb = new StringBuilder ( key ) ;
      sb.Replace(@"HKEY_CLASSES_ROOT\","") ;
    
      // Open the CLSID\{guid} key for write access
      RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(),true);
    
      // And create the 'Control' key - this allows it to show up in 
      // the ActiveX control container 
      RegistryKey ctrl = k.CreateSubKey ( "Control" ) ; 
      ctrl.Close ( ) ;
    
      // Next create the CodeBase entry - needed if not string named and GACced.
      RegistryKey inprocServer32 = k.OpenSubKey ( "InprocServer32" , true ) ; 
      inprocServer32.SetValue ( "CodeBase" , Assembly.GetExecutingAssembly().CodeBase ) ; 
      inprocServer32.Close ( ) ;
    
      // Finally close the main key
      k.Close ( ) ;
    }
    The RegisterClass function is attributed with ComRegisterFunction - this static method will be called when the assembly is registered for COM Interop. All I do here is add the 'Control' keyword to the registry, plus add in the CodeBase entry.

    CodeBase is interesting - not only for .NET controls. It defines a URL path to where the code can be found, which could be an assembly on disk as in this instance, or a remote assembly on a web server somewhere. When the runtime attempts to create the control, it will probe this URL and download the control as necessary. This is very useful when testing .NET components, as the usual caveat of residing in the same directory (etc) as the .EXE does not apply.

    C#
    [ComUnregisterFunction()]
    public static void UnregisterClass ( string key )
    {
      StringBuilder sb = new StringBuilder ( key ) ;
      sb.Replace(@"HKEY_CLASSES_ROOT\","") ;
    
      // Open HKCR\CLSID\{guid} for write access
      RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(),true);
    
      // Delete the 'Control' key, but don't throw an exception if it does not exist
      k.DeleteSubKey ( "Control" , false ) ;
    
      // Next open up InprocServer32
      RegistryKey inprocServer32 = k.OpenSubKey ( "InprocServer32" , true ) ;
    
      // And delete the CodeBase key, again not throwing if missing 
      k.DeleteSubKey ( "CodeBase" , false ) ;
    
      // Finally close the main key 
      k.Close ( ) ;
    }

    The second function will remove the registry entries added when (if) the class is unregistered - it's always a good suggestion to tidy up as you go.

Now you are ready to compile & test your control.

Testing the Control

For this example I have chosen tstcon32.exe, which is available with the installation of .NET. The main reason I've used this rather than VB6 is that I don't have VB6 anymore.

Inserting the Control

First up you need to insert your control, so to do that choose Edit -> Insert New Control, and choose your control from the dropdown...

Image 3

This will result in a display as shown at the top of the article, if you're following along with my example code.

Testing Methods

The example control only includes one method, 'Question'. To test this within TstCon32, choose Control -> InvokeMethods from the menu, and select the method you want to call. Note that because I defined the interface as AutoDual, I get gazillions of methods. If you implement an interface and expose this as the default interface then the list of methods will be more manageable.

Image 4

Click on the 'Invoke' button will execute the method, which in this instance displays the obligatory message box.

Wrap Up

Dropping support for creating ActiveX controls from Windows Forms controls is a pain, and one decision I wish Microsoft had not made.

This article presents one way of exposing .NET controls as ActiveX controls, and seems to work OK. Having said that, I've not exhaustively tested this and who knows what bugs might be lurking in there. I haven't delved into events yet, nor property change notifications, so there's some fun to be had there if you like that sort of thing.

The .NET framework truly is the best thing since sliced bread, but the lack of support for creating ActiveX controls from Windows Forms controls is inconvenient. There are many applications out there (ours included) which can be extended with ActiveX controls. It would be nice given the rest of the support in the framework to be able to expose Windows Forms controls to ActiveX containers, and maybe someday the support will be available.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Founder MS Application Development Consulting Ltd
United Kingdom United Kingdom
I started work in 1989 for LabSystems, based in Altrincham. I had originally expected to stay for six months, but the job was so good I stayed for 12.5 years.

In December 2001 I joined Microsoft as an Application Development Consultant, where I spent lots of time assisting customers with their use of Microsoft technologies.

I left in June 2011 to start my own business, and I do contract development, knowledge sharing and bespoke application development.

Comments and Discussions

 
GeneralCompatibility with RegAsm and some containers Pin
E11m3-Feb-06 20:44
E11m3-Feb-06 20:44 
GeneralRe: Compatibility with RegAsm and some containers Pin
wangxufei2-Mar-06 20:41
wangxufei2-Mar-06 20:41 
GeneralRe: Compatibility with RegAsm and some containers Pin
E11m3-Mar-06 7:06
E11m3-Mar-06 7:06 
QuestionRe: Compatibility with RegAsm and some containers Pin
.Suchit15-Dec-06 1:55
.Suchit15-Dec-06 1:55 
GeneralEvents needed work - otherwise Great Job Pin
CraigSBoyd15-Jan-06 21:59
CraigSBoyd15-Jan-06 21:59 
GeneralRe: Events needed work - otherwise Great Job Pin
ndecreve10-Feb-06 0:29
ndecreve10-Feb-06 0:29 
GeneralRe: Events needed work - otherwise Great Job Pin
CraigSBoyd10-Feb-06 0:51
CraigSBoyd10-Feb-06 0:51 
GeneralRe: Events needed work - otherwise Great Job Pin
ndecreve10-Feb-06 2:52
ndecreve10-Feb-06 2:52 
Hi Craig,

I'm sorry but it does not seems to work with VB6. I've followed your steps and get the following C# code:
using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;

namespace COMTest
{
	[ComVisible(false)]
	public delegate void HelloClicked();
	
	[Guid("70B9F4F4-0285-4aae-B64E-DE57BDBF49C5")]
	[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
	public interface DMyCOMObject
	{
		[DispIdAttribute(1)]
		void Clicked();
	}

	//Not usefull here, but will be later if all this works ;-)
	[Guid("CAE73FF2-2D47-4677-B8EA-3E0FF12E4B0D")]
	[InterfaceType(ComInterfaceType.InterfaceIsDual)]
	public interface IMyCOMObject
	{

	}

	
	[Guid("F65B3579-FEAA-4da5-BABA-1B9D195307FF")]
	[ClassInterface(ClassInterfaceType.None)]
	[ComSourceInterfaces(typeof(DMyCOMObject))]
	[ProgId("COMTest.MyCOMObject")]
	public class MyCOMObject : System.Windows.Forms.UserControl, IMyCOMObject
	{
		private System.Windows.Forms.Button button1;
		private System.ComponentModel.Container components = null;

		public event HelloClicked Clicked;
		

		public MyCOMObject()
		{
			InitializeComponent();
		}


		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if( components != null )
					components.Dispose();
			}
			base.Dispose( disposing );
		}

		#region Component Designer generated code
		private void InitializeComponent()
		{
			this.button1 = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// button1
			// 
			this.button1.Location = new System.Drawing.Point(72, 16);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(144, 32);
			this.button1.TabIndex = 0;
			this.button1.Text = "Try to get an event";
			this.button1.Click += new System.EventHandler(this.button1_Click);
			// 
			// MyCOMObject
			// 
			this.Controls.Add(this.button1);
			this.Name = "MyCOMObject";
			this.Size = new System.Drawing.Size(280, 56);
			this.Load += new System.EventHandler(this.MyCOMObject_Load);
			this.ResumeLayout(false);

		}
		#endregion


		private void button1_Click(object sender, System.EventArgs e)
		{
			if(Clicked != null)
			{
				MessageBox.Show("Clicked not null");
				Clicked();
			}
			else
			{
				MessageBox.Show("Clicked null");
			}
		}

		private void MyCOMObject_Load(object sender, System.EventArgs e)
		{
		
		}


		//copyright Morgan Skinner, 2001
		[ComRegisterFunction()]
		public static void RegisterClass(string key)
		{
			// Strip off HKEY_CLASSES_ROOT\ from the passed key as I don't need it
			StringBuilder sb = new StringBuilder(key);
			sb.Replace(@"HKEY_CLASSES_ROOT\", "");
			// Open the CLSID\{guid} key for write access
			RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(), true);
			// And create the 'Control' key - this allows it to show up in 
			// the ActiveX control container 
			RegistryKey ctrl = k.CreateSubKey("Control");
			ctrl.Close();
			// Next create the CodeBase entry - needed if not string named and GACced.
			RegistryKey inprocServer32 = k.OpenSubKey("InprocServer32", true);
			inprocServer32.SetValue("CodeBase", Assembly.GetExecutingAssembly().CodeBase);
			inprocServer32.Close();
			// Finally close the main key
			k.Close();
		}

		//copyright Morgan Skinner, 2001
		[ComUnregisterFunction()]
		public static void UnregisterClass ( string key )
		{
			StringBuilder sb = new StringBuilder ( key ) ;
			sb.Replace(@"HKEY_CLASSES_ROOT\","") ;
			// Open HKCR\CLSID\{guid} for write access
			RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(),true);
			// Delete the 'Control' key, but don't throw an exception if it does not exist
			k.DeleteSubKey ( "Control" , false ) ;
			// Next open up InprocServer32
			RegistryKey inprocServer32 = k.OpenSubKey ( "InprocServer32" , true ) ;
			// And delete the CodeBase key, again not throwing if missing 
			k.DeleteSubKey ( "CodeBase" , false ) ;
			// Finally close the main key 
			k.Close ( ) ;
		}
	}
}


I'm using the following AssemblyInfos.cs
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("My COM Test")]
[assembly: AssemblyDescription("COM Test Library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DevHood")]
[assembly: AssemblyProduct("COMTest")]
[assembly: AssemblyCopyright("Copyright 2002")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]		
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile(@"..\..\KeyFile.snk")]
[assembly: AssemblyKeyName("")]
[assembly: Guid("B58D7C8C-2E2D-4aa6-8EAF-CF7CB448E353")]
[assembly: ComVisible(true)]


I've got the keyfile and I've checkmark the "Register for COM interop" checkbox on the Build page.

Everything's fine until now. I'm then using the following script in VB6:

Option Explicit

Dim WithEvents objComTest As VBControlExtender

'should work but does not
Private Sub objComTest_ObjectEvent(Info As EventInfo)
    Select Case Info.Name
        Case "Clicked"
            MsgBox "Event!"
        Case Else
            MsgBox "Event!"
    End Select
End Sub

Private Sub Form_Load()
    Licenses.Add "COMTest.MyCOMObject", "xyz"
    Set objComTest = Controls.Add("COMTest.MyCOMObject", "MyComTest")
    objComTest.Visible = True
End Sub


Which doesn't catch event. If you try it, you'll find that in fact the VB6 does not connect or register to the C# so that the Clicked is null when we push the button

I can send you the files if you like...
If someone find the answer, it will help a lot of people, since I've found the exact problem in some other forum...

Have you an idea of the problem? It seems eather it is a small thing that is missing or it is not possible to catch events in VB6 (I'll prefer the first one Smile | :) ).

Thanks in advance


Nicolas Décrevel

-- modified at 8:53 Friday 10th February, 2006
GeneralRe: Events needed work - otherwise Great Job Pin
tabyss16-Feb-06 22:54
tabyss16-Feb-06 22:54 
GeneralRe: Events needed work - otherwise Great Job Pin
Michal Vlk21-Feb-07 7:01
Michal Vlk21-Feb-07 7:01 
GeneralRe: Events needed work - otherwise Great Job Pin
Madhu babu T11-Jun-06 22:42
Madhu babu T11-Jun-06 22:42 
GeneralRe: Events needed work - otherwise Great Job Pin
ElleryFamilia12-Jun-06 6:14
ElleryFamilia12-Jun-06 6:14 
AnswerRe: Events needed work (solved) - otherwise Great Job Pin
MrKagami2-Nov-08 8:36
MrKagami2-Nov-08 8:36 
GeneralRe: Events needed work (solved) - otherwise Great Job Pin
Camilo Sanchez3-Aug-10 10:37
Camilo Sanchez3-Aug-10 10:37 
General.net activex used in vb6 or .net control wrapped in MFC Pin
Nat2412-Jan-06 16:21
Nat2412-Jan-06 16:21 
GeneralRe: .net activex used in vb6 or .net control wrapped in MFC Pin
Nat2415-Jan-06 8:45
Nat2415-Jan-06 8:45 
GeneralProblems adding control to InfoPath 2003 Pin
netoec8423-Oct-05 3:33
netoec8423-Oct-05 3:33 
GeneralUserControl references another DLL Pin
Omri Shaked12-Apr-05 3:07
Omri Shaked12-Apr-05 3:07 
GeneralRe: UserControl references another DLL Pin
RipplingCreek1-Aug-05 13:36
RipplingCreek1-Aug-05 13:36 
GeneralImportant note on using this with Visual Basic 6 Pin
GabM27-Oct-04 13:31
GabM27-Oct-04 13:31 
GeneralRe: Important note on using this with Visual Basic 6 Pin
Nat2421-Dec-05 10:14
Nat2421-Dec-05 10:14 
GeneralRe: Important note on using this with Visual Basic 6 Pin
ndecreve10-Feb-06 0:23
ndecreve10-Feb-06 0:23 
GeneralUsing control in MS Word Pin
bondarch24-Sep-04 11:58
bondarch24-Sep-04 11:58 
GeneralRe: Using control in MS Word Pin
Phil Crosby11-Feb-06 18:21
Phil Crosby11-Feb-06 18:21 
QuestionCan this hold another activex control? Pin
Aibynn20-May-04 19:09
Aibynn20-May-04 19:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.