Create activex with .net

Page 1

CodeProject: Create ActiveX in .NET Step By Step. Free source code a...

1 di 5

Languages » C# » COM Interop

http://www.codeproject.com/KB/cs/CreateActiveXDotNet.aspx?displ...

C# (C# 1.0, C# 2.0, C#), Javascript, HTML, .NET (.NET, .NET 1.0, .NET 1.1, .NET 2.0), Dev

License: The Code Project Open License (CPOL)

Create ActiveX in .NET Step By Step By Michał Kosmala

Article describes how to create ActiveX in .NET and how to use it on HTML page step by step.

Posted: 4 Mar 2008 Updated: 4 Mar 2008 Views: 17,884 Bookmarked: 47 times

Note: This is an unedited reader contribution 9 votes for this Article. Popularity: 3.08 Rating: 3.23 out of 5

1 2 3 4 5

Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Download ActiveXSourceCode.zip - 30.03 KB Download Setup - 286 B Download Web - 899 B

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. First step you have to do is to create ActiveX control :). Good introduction to this subject you can find here: http://www.codeproject.com/cs/miscctrl/exposingdotnetcontrols.asp This article describes how to create and expose windows forms on the web site. Since there is no such support on 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 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 – Unique GUID that will expose our class to be used as COM object. To create new GUID you can use 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:

27/08/2008 18.25


CodeProject: Create ActiveX in .NET Step By Step. Free source code a...

2 di 5

http://www.codeproject.com/KB/cs/CreateActiveXDotNet.aspx?displ...

///<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">Tke 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 RegisterClass method and regasm /u MyAssemblie.dll which will run 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 .NET SDK): sn –k Kosmala.Michal.ActiveXReport.snk Once you create 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 on 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

27/08/2008 18.25


CodeProject: Create ActiveX in .NET Step By Step. Free source code a...

3 di 5

http://www.codeproject.com/KB/cs/CreateActiveXDotNet.aspx?displ...

the place where installation program (wrapped in CAB) should be placed. Let us now forget for a moment about codebase section since we are doing every thing 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 start to actually use 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 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 any name you can think. Assigning variables works both ways. You can also read from ActiveX field using JavaScript Remember to set proper security values in your IE that will allow running ActiveX.

3) Creating .cab component Now it is time to create cab file that will be launched when 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). 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: http://support.microsoft.com/kb/310618 Now. The important thing abut 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="$"""on"""">"""on"""">CHICAGO$" 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 section that is defined in 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 we need we can create cab file using cabsdk by using command: cabarc.exe n OurActiveX.cab OurActiveX.inf setup.exe Voila. Our basic ActiveX with distribution property is ready. Now for something more sophisticated :).

27/08/2008 18.25


CodeProject: Create ActiveX in .NET Step By Step. Free source code a...

4 di 5

http://www.codeproject.com/KB/cs/CreateActiveXDotNet.aspx?displ...

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 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 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 have to be signed and registered with additional parameter “/tlb”. This is very simple ActiveX but it can call any WinForms control or application that your user have 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.

27/08/2008 18.25


CodeProject: Create ActiveX in .NET Step By Step. Free source code a...

5 di 5

http://www.codeproject.com/KB/cs/CreateActiveXDotNet.aspx?displ...

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

About the Author Michał Kosmala

ASP.NET Developer since 2004 Occupation: Web Developer Location:

Poland

Discussions and Feedback 59 messages have been posted for this article. Visit http://www.codeproject.com/KB/cs /CreateActiveXDotNet.aspx to post and view comments on this article, or click here to get a print view with messages. PermaLink | Privacy | Terms of Use Last Updated: 4 Mar 2008 Editor:

Copyright 2008 by Michał Kosmala Everything else Copyright © CodeProject, 1999-2008 Web10 | Advertise on the Code Project

27/08/2008 18.25


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.