Click here to Skip to main content
11,576,060 members (54,060 online)
Click here to Skip to main content

Create ActiveX in .NET Step by Step

, 4 Mar 2008 CPOL 644.7K 43.6K 223
Rate this:
Please Sign up or sign in to vote.
Article describes how to create ActiveX in .NET and how to use it on an HTML page step by step.

Introduction

At my job, I have had a project where I needed to deliver a solution for creating, distributing and running ActiveX controls written in .NET. This article summarizes all of it. Everything that is in this article can be found on the Web, but believe me this is not so easy;).

Using the Code

  • ActiveXSourceCode.zip - Contains .NET source code for the ActiveX
  • Setup.zip - Contains example of the *.ini file needed to create CAB
  • Web.zip - Example of the HTML file that embeds ActiveX object

So Let Us Start...

1) Creating .NET ActiveX

The first step you have to do is to create the ActiveX controlSmile | :) .

You can find a good introduction to this subject here.

This article describes how to create and expose Windows Forms on the Web site. Since there is no such support in the .NET Framework, WinForms are wrapped into ActiveX which is exactly what we need. In summary, what we need is to create a class that will be marked with those attributes:

[ProgId("MyClassName")]

[Guid("MyGUID")] sdf 
[ComVisible(true)] 

Where:

  • ProgId is the unique name of the class that will be exposed as COM object
  • ClassInterface is the type of the COM interface that will wrap our .NET class
  • Guid is the unique GUID that will expose our class to be used as COM object. To create a new GUID, you can use the tool in Visual Studio Tools -> Create GUID
  • ComVisible tells that our class can be used as COM object

Registering COM object means that you need to make some entries in the registry. You can do this manually or you can write methods in your ActiveX that will do that for you when you register it with tools like regasm:

///<summary>
///Register the class as a control and set its CodeBase entry
///</summary>
///<param name="key">The registry key of the control</param>
[ComRegisterFunction()]
public static void RegisterClass ( string key )
{
.
.
.
}

///<summary>
///Called to unregister the control
///</summary>
///<param name="key">The registry key</param>
[ComUnregisterFunction()]
public static void UnregisterClass ( string key)
{
.
.
.
}

Having those methods implemented, you can now use command: regasm /codebase MyAssemblie.dll which will run the RegisterClass method and regasm /u MyAssemblie.dll which will run the UnregisterClass method.

To expose .NET methods and properties in your class to be available as COM methods and properties, you have to add markup [ComVisible(true)] to them, i.e.:

[ComVisible(true)]
public void Open()
{
. 
    System.Windows.Forms.MessageBox.Show(MyParam);
.
}

[ComVisible(true)]
public string MyParam
{
    get
    {          
        return myParam;
    } 
    set
    { 
        myParam = value;
    }
} 

You have to remember that your assembly must be signed using strong name key, this way you will have the ability to use more complicated controls, assemblies and features (like passing events back to the browser). To create new SNK, you can use tool: sn.exe (you can find it in the .NET SDK):

sn –k Kosmala.Michal.ActiveXReport.snk

Once you create a strong name key, copy it into your project path and put path to it in the AssemblyInfo.cs file in:

[assembly:AssemblyKeyFile("../../Kosmala.Michal.ActiveXReport.snk")] 

Once you have your class registered as COM, you can now use it in your Web page.

2) Using ActiveX on the HTML Page

To start using your ActiveX in the HTML file, you just have to put one tag:

<OBJECT id="OurActiveX" name=”OurActiveX" classid="clsid:MyGuid" 
	VIEWASTEXT codebase="OurActiveX.cab">

Where:

  • id and name are values that will be used to access our ActiveX from JavaScript
  • classid is the GUID of our ActiveX that we have put in [Guid("MyGUID")] section of our C# code
  • Codebase is the path to the file which should be launched when ActiveX with our GUID is not found. This is the place where the installation program (wrapped in CAB) should be placed.

Let us now forget for a moment about the codebase section since we are doing everything on our computer and we can register ActiveX with using regasm.

Now that our Web page knows what kind of ActiveX we want to use, we can actually start using it.

To do that, we just need to write some JavaScript code on the page. This code can look something like this:

<script language="javascript">

//Passing parameters to ActiveX object
function OpenActiveX()
{
    try
    {
        document.OurActiveX.MyParam = "Hi I am here."
        document.OurActiveX.Open();
    }
    catch(Err)
    { 
        alert(Err.description);
    }

    OpenActiveX();
}
</script> 

This script will assign value to MyParam and invoke the Open() method from our C# code which will return open MessageBox with “I am here” text. Open is just a name of the method, it can be named anything that you can think of.

Assigning variables works both ways. You can also read from ActiveX field using JavaScript.

Remember to set proper security values in your Internet Explorer that will allow running ActiveX.

3) Creating .cab Component

Now it is time to create the CAB file that will be launched when the browser won't find our ActiveX registered on the system. First of all, you have to create a setup program that will either be MSI or it will wrap MSI into setup.exe file. I have done this by using InstallShield application because this is what my company standard was, but you can use Visual Studio to do that (although I have never tested it). The important thing is that your setup has to register your ActiveX on a target computer. This might require having administration privileges.

Once you have your setup, you have to create CAB. To do that you can use cabsdk which you can find here.

Now, the important thing about our CAB is to attach not only our setup file but also *.ini file that will describe what CAB contains and what file should be launched. Our OurActiveX.ini can look something like this:

[version]
    signature="$<place w:st="""""on""""" /><city w:st="""""on""""" />CHICAGO</city /></place />$"
    AdvancedINF=2.0 
[Add.Code]
    setup.exe=setup.exe
[setup.exe]
    file-win32-x86=thiscab
    clsid={MyGuid}

Where:

  • [Add Code] section describes what sections of the file are mapped to what file. In our case, there is only one setup.exe file that is mapped by section with the same name.
  • [setup.exe] section is the one that is defined in the previous section. It is saying that file that it is mapped to should be launched when accessed with proper clsid. In this case, this is the MyGuid that is defined in our C# code and also in <OBJECT> tag.

Now that we have all files that we need, we can create CAB file using cabsdk by using the command:

cabarc.exe n OurActiveX.cab OurActiveX.inf setup.exe

Voila. Our basic ActiveX with distribution property is ready.

Now for something more sophisticatedSmile | :) .

4) Invoking JavaScript Methods from ActiveX

It might be necessary to send an event from ActiveX that JavaScript will catch, i.e. when you want to control redirection of the Web page when you close ActiveX.

To do that, you have to update your C# code. You have to add a new interface and a new delegate:

public delegate void ControlEventHandler(string redirectUrl);

/// <summary>
/// This interface shows events to javascript
/// </summary>
[Guid(NewGuid)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ControlEvents
{
    //Add a DispIdAttribute to any members in the source interface 
    //to specify the COM DispId.
    [DispId(0x60020000)]
    void OnClose(string redirectUrl);
} 

This code creates an interface wrapper that will be visible outside as COM object. Every new event that will be available for COM must be marked DispId attribute.

(Creating .NET to COM objects http://www.csharphelp.com/archives/archive281.html)

Now we have to inherit our new interface in ActiveX control:

[ClassInterface(ClassInterfaceType.AutoDual), 
	ComSourceInterfaces(typeof(ControlEvents))]

Since we are implementing ControlEvents interface, now we have to create OnClose event in our class which we can raise in our ActiveX:

public event ControlEventHandler OnClose;

After compilation of this code, we have to register our ActiveX control (regasm) with additional parameter “/tlb” which will extract tlb COM library from our DLL and it will register it on our system:

regasm /codebase /tlb MyAssemblie.dll

Having this kind of code, we can add handling of this event in JavaScript:

<script language="javascript">
function OurActiveX::OnClose(redirectionUrl)
    { 
        window.location = hostUrl + "/" + redirectionUrl;
    }
</script>

Event is being attached only after the whole page has been loaded, so to use it we have to change the way of invoking JavaScript function: OpenActiveX. Now we have two ways of doing it:

  1. We can attach our function to i.e. button and our ActiveX will run when we will click on it:

    <input type=button onclick=javascript:OpenActiveX()>
  2. If we want that it will be started automatically after the page will be loaded, we have to attach our function to body event “onload”:

    <body onload=OpenActivex()>

You have to remember that your ActiveX assembly has to be signed and registered with additional parameter “/tlb”.

This is a very simple ActiveX but it can call any WinForms control or application that your user has rights to.

Points of Interest

As you can see, it is very easy to create and distribute ActiveX in .NET, but it is very difficult to find right answers on the Web probably because not so many people are using ActiveX nowadays.

I hope that this article will cut your search time as much as possible.

History

  • 4th March, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Michał Kosmala
Web Developer
Poland Poland
ASP.NET Developer since 2004

You may also be interested in...

Comments and Discussions

 
QuestionNot working on client machine Pin
Nader El Masry23-Dec-12 5:01
memberNader El Masry23-Dec-12 5:01 
GeneralMy vote of 5 Pin
Yugan_SA3-Dec-12 23:05
memberYugan_SA3-Dec-12 23:05 
QuestionActiveX might not be safe Pin
Joni_7825-Nov-12 7:19
memberJoni_7825-Nov-12 7:19 
QuestionCab file for registering a dll in windows 7 using web aplication Pin
Jeyamani23-Nov-12 17:53
memberJeyamani23-Nov-12 17:53 
QuestionUnable Create Cab file Pin
evreddy46117-Oct-12 20:01
memberevreddy46117-Oct-12 20:01 
GeneralMy vote of 1 Pin
Jecka2-Oct-12 5:01
memberJecka2-Oct-12 5:01 
QuestionMember not Found Pin
sri43713-Jul-12 23:31
membersri43713-Jul-12 23:31 
QuestionAdvice ,,, Pin
abojanty10-Jul-12 11:17
memberabojanty10-Jul-12 11:17 
QuestionActiveX control is not working in browser Pin
thamim30-Apr-12 2:57
memberthamim30-Apr-12 2:57 
GeneralMy vote of 5 Pin
Edmo Costa27-Apr-12 10:45
memberEdmo Costa27-Apr-12 10:45 
QuestionJavascript Invoke the Activex mehtod byte MyFunc( ref byte InputParameter , ref byte OutputParameter) Pin
f7anty18-Feb-12 0:46
memberf7anty18-Feb-12 0:46 
QuestionRegistring ActiveX components using RegisterClass and UnRegisterClass methods Pin
Member 827668229-Sep-11 22:31
memberMember 827668229-Sep-11 22:31 
AnswerRe: Registring ActiveX components using RegisterClass and UnRegisterClass methods Pin
duwkes24-Mar-12 4:43
memberduwkes24-Mar-12 4:43 
http://msdn.microsoft.com/en-us/library/aa751972(v=vs.85).aspx[^]

Note the section about self registration
GeneralI am getting error Pin
bijumanis24-Mar-11 20:45
memberbijumanis24-Mar-11 20:45 
GeneralMy vote of 5 Pin
guibhz5-Mar-11 3:13
memberguibhz5-Mar-11 3:13 
QuestionCan I make this ActiveX component to run as singleton? Pin
VasuJoe10-Nov-10 20:52
memberVasuJoe10-Nov-10 20:52 
GeneralMy vote of 5 Pin
serhanak19-Oct-10 9:26
memberserhanak19-Oct-10 9:26 
QuestionCreating an Outproc ActiveX? Pin
Member 362156615-Jul-10 21:04
memberMember 362156615-Jul-10 21:04 
AnswerRe: Creating an Outproc ActiveX? Pin
ilengyel19-Jul-10 15:29
memberilengyel19-Jul-10 15:29 
General"Object doesn't support this property or method" Exception Pin
Brad North11-May-10 19:05
memberBrad North11-May-10 19:05 
GeneralRe: "Object doesn't support this property or method" Exception Pin
javier.alpizar15-Jul-10 14:24
memberjavier.alpizar15-Jul-10 14:24 
GeneralRe: "Object doesn't support this property or method" Exception Pin
Safaer9-Sep-10 11:35
memberSafaer9-Sep-10 11:35 
GeneralRe: "Object doesn't support this property or method" Exception Pin
AbdelRahman Doghish26-Oct-10 2:35
memberAbdelRahman Doghish26-Oct-10 2:35 
GeneralRe: "Object doesn't support this property or method" Exception Pin
AbdelRahman Doghish27-Oct-10 0:42
memberAbdelRahman Doghish27-Oct-10 0:42 
GeneralRe: "Object doesn't support this property or method" Exception Pin
setrweda_n18-Nov-10 7:58
membersetrweda_n18-Nov-10 7:58 
GeneralRe: "Object doesn't support this property or method" Exception Pin
AbdelRahman Doghish9-Nov-10 0:10
memberAbdelRahman Doghish9-Nov-10 0:10 
GeneralRe: "Object doesn't support this property or method" Exception Pin
GONZALOEL22-Nov-10 17:18
memberGONZALOEL22-Nov-10 17:18 
GeneralRe: "Object doesn't support this property or method" Exception Pin
panthamm3-Feb-11 10:35
memberpanthamm3-Feb-11 10:35 
GeneralRe: "Object doesn't support this property or method" Exception Pin
Oswdom3-May-11 12:39
memberOswdom3-May-11 12:39 
GeneralProblems with locally generated GUID Pin
naorem21-Mar-10 23:17
membernaorem21-Mar-10 23:17 
GeneralWinodws7 and IE8 Pin
chunwaitam10-Feb-10 15:07
memberchunwaitam10-Feb-10 15:07 
GeneralRe: Winodws7 and IE8 Pin
zwu_ca25-Oct-10 17:36
memberzwu_ca25-Oct-10 17:36 
GeneralRe: Winodws7 and IE8 Pin
Rob@Love2Code21-Jan-11 2:25
memberRob@Love2Code21-Jan-11 2:25 
QuestionThis website wants to run the following add-on: 'Control name is not available' from 'Unknown Publisher' Pin
jomygeorge21-Jan-10 22:24
memberjomygeorge21-Jan-10 22:24 
AnswerRe: This website wants to run the following add-on: 'Control name is not available' from 'Unknown Publisher' [modified] Pin
eweewf8-Apr-10 14:14
membereweewf8-Apr-10 14:14 
GeneralCreate ActiveX in .NET Step by Step Pin
akhil kumar jaiswal23-Dec-09 22:14
groupakhil kumar jaiswal23-Dec-09 22:14 
GeneralIE 6 Application error Pin
Veronica F2-Nov-09 9:33
memberVeronica F2-Nov-09 9:33 
QuestionMay I debug this component ? Pin
maxpanella30-Oct-09 6:48
membermaxpanella30-Oct-09 6:48 
GeneralSecurity Problem Pin
maxpanella22-Oct-09 9:09
membermaxpanella22-Oct-09 9:09 
AnswerRe: Security Problem Pin
maxpanella30-Oct-09 6:53
membermaxpanella30-Oct-09 6:53 
QuestionCan i use visual studio cab ... Pin
janakaDG28-Sep-09 0:19
memberjanakaDG28-Sep-09 0:19 
AnswerRe: Can i use visual studio cab ... Pin
YasirLaghari14-Jan-10 5:43
memberYasirLaghari14-Jan-10 5:43 
Questionwill it work with tomcat server? Pin
crazy1boy10-Sep-09 1:30
membercrazy1boy10-Sep-09 1:30 
AnswerRe: will it work with tomcat server? Pin
dwipayan11-Oct-09 19:43
memberdwipayan11-Oct-09 19:43 
GeneralActivex uninstall doesn't remove the CAB from the IE Temporary storage. Pin
dwipayan9-Sep-09 23:13
memberdwipayan9-Sep-09 23:13 
QuestionWhat steps do you do in installShield? Pin
sizam21-Aug-09 21:53
membersizam21-Aug-09 21:53 
AnswerRe: What steps do you do in installShield? Pin
cthulhi27-Aug-09 9:11
membercthulhi27-Aug-09 9:11 
QuestionVS2005 SP1 Paradox Pin
eugene_sh20-Aug-09 1:08
membereugene_sh20-Aug-09 1:08 
Generalnot work for web server Pin
kylechan5-Aug-09 21:14
memberkylechan5-Aug-09 21:14 
QuestionHow to make COM visible to others Pin
prashant_1444-Aug-09 0:40
memberprashant_1444-Aug-09 0:40 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 4 Mar 2008
Article Copyright 2008 by Michał Kosmala
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid