Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » COM Interop » Writing an ActiveX Control in .NET

Writing an ActiveX Control in .NET

In this example, I will walk you through creating an ActiveX control that will show a simple user interface and accept input from a web page.

Total page views :  272204
Total downloads :  5730
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ActiveXDotNet.zip
 
Become a Sponsor


Interviews

Software developers have used ActiveX controls on their web pages to add advanced functionality to the web experience. With my migration from a Visual Basic 6 world to a Microsoft .NET C# world, I had some question as to how I can create an ActiveX control with .NET. After some research I found out that the solution is really quite simple. Create a Windows control project in Visual Studio .NET and expose an interface to the COM world.

In this example, I will walk you through creating an ActiveX control that will show a simple user interface and accept input from a web page. This process will involve the following steps:

  1. Create an assembly (class library project) that contains an item of type User Control.
  2. Expose an interface for the control.
  3. Embed the user control into a web page.
  4. Transfer data from a web form to the control and display the data on the control.

Step 1: Create an assembly.

You can use the example provided for download, or simply create your own project from scratch. In this section I will outline everything you need to do in order to properly create your assembly.

First, you create a new project of type Class Library. Name the class library ActiveXDotNet.



Once the project is created, delete the Class1.cs file from your project as it will not be necessary. Next, add a User Control to the project by right clicking on the project in your solution explorer, choose Add, then User Control. Name your user control myControl.



On the user control, add some UI elements, and a text box control named txtUserText. The txtUserText control will display the user data that is typed into the web form. This will demonstrate how to pass data to your User Control.

When you are done adding your user interface to the control we now have to add a key element to the control, an Interface. The interface will allow COM/COM+ objects to know what properties they can use. In this case, we are going to expose one public property named UserText. That property will allow us to set the value of the text box control.

Step 2: Expose the Interface for the control.

First, create a private String to hold the data passed from the web form to the control:

private String mStr_UserText;

Place this String just inside the Class myControl.

Next, we will create a public property. The web page will use this property to pass text back to your control. This property will allow reading and writing of the value mStr_UserText.

public String UserText
{
get { return mStr_UserText; }
set
{
mStr_UserText =
value;
//Update the text box control value also.
txtUserText.Text = value;
}
}

In this example, you will note the extra code in the set section of the public property. When a value is passed from the web form to the control we will set the private String value equal to the value passed to the property. In addition, we are simply going to modify the value of the Text Box control directly. Typically you would NOT do this. Instead, you would raise an event and then validate the data being passed by examining the private variable mStr_UserText. Then you would set the value of the Text Box Control. However, that would add significant code to this example and for simplicity sake I am omitting that security precaution.

Now that you have a public property that .NET assemblies can use, you need to make that property available to the COM world. We do this by creating an Interface and making the myControl class inherit the interface. This will allow COM objects to see what properties we have made available.

Your code will now look like this:

namespace ActiveXDotNet
{
public interface AxMyControl
{
String UserText {
set; get ; }
}
public class myControl : System.Windows.Forms.UserControl, AxMyControl
{
private String mStr_UserText;
public String UserText
{
get { return mStr_UserText; }
set
{
mStr_UserText =
value;
//Update the text box control value also.
txtUserText.Text = value;
}
}
...

Notice that we now have an interface defined, the interface tells COM/COM+ that there is a public property available for use that is of type String and is readable (get) and writeable (set). All we do now is have the Class myControl inherit the interface and viola! We have a .NET assembly that acts like an ActiveX Control.

Step 3: Embed the user control in a web page.

The last thing we do now is use the control in an example web page.

<html>
 <body color=white>
  <hr>  
      <font face=arial size=1>
       <OBJECT id="myControl1" name="myControl1" classid="ActiveXDotNet.dll#ActiveXDotNet.myControl" width=288 height=72>
       </OBJECT>
     </font>  
     <form name="frm" id="frm">
       <input type="text" name="txt" value="enter text here"><input type=button value="Click me" onClick="doScript();">
      </form>
  <hr>
 </body> 
<script language="javascript">
      function doScript()
       {
        myControl1.UserText = frm.txt.value;
       }
</script>
</html>

You will notice in the HTML code above, that you call your .NET assembly very similar to an ActiveX control; however there is no GUID, and no .OCX file. Your CLASSID is now the path to your DLL and the Namespace.Classname identifier. Refer to the code above to understand the syntax of the CLASSID object tag property. Place the HTML file and your DLL in the same directory on your web server and navigate to the HTML document. (Do not load the HTML document by double clicking on it, navigate to it in your browser by using the Fully Qualified URL.) *NOTE: You might need to add your web server to your Trusted Sites list in your Internet Explorer browser.

Step 4: Transfer data from the web form to the user control.

When you load the HTML page, your control should load into the page and you will see a web form with a text box and a button. In this example, if you type some text into the text box and click the button, it will use JavaScript to send the text from the web page form, to the User Control that you just built. Your User Control will then display the text in the Text Box control that I on the form.

Where do I go from here?

There are many issues that you should investigate in order to properly create User Controls that work on a web page. .NET Security plays a big part in what you can actually do within the confines of your code. You should also investigate code signing your control.


Login to add your contents and source code to this article
 About the author
 
David Sandor
David Sandor is an Enterprise Software Architect currently working at a Fortune 100 company. He has been certified by serveral sources in the following areas: MCSE, MCSD, Linux, C#, JAVA, Visual Basic 6. David has 10 years of professional development experience.
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.
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.
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.
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.
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ActiveXDotNet.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
\r\n
Reply | Email | Delete | Modify | 
','9600','',8,7,0,0,0,0,1,0,'','ArticleComments','',false,62,0,1,1,0,'ArticleComments','ArticleComments',0,'t62',0,1,{}]];
Running example on a different web server than IIS by Patrick On February 10, 2006
Will this example run on a different web server than IIS?  I am not having any success with running it outside of an IIS web server.

Any assistance in running it elswhere would be greatly appreciated, I am looking to run it on Tomcat.
Reply | Email | Delete | Modify | 
Re: Running example on a different web server than IIS by Christopher On September 9, 2007

For a servlet container like Tomcat you will probably need to register the "dll" suffix so that it's served with the correct mime type. In your webapp's web.xml file (or in the global Tomcat web.xml in tomcat/conf) add the following lines:

    <mime-mapping>
      <extension>dll</extension>
      <mime-type>application/x-msdownload</mime-type>
    </mime-mapping>

You may need to restart Tomcat for the changes to take effect.

The wrong mime type will result in the <OBJECT> showing up with the correct height and width, but with only a little red "x" in the upper left hand corner instead of your control.

Other stuff I had to do:

  • Used gacutil /cdl to clear the cache every time I changed the build settings for the DLL.
  • Made sure that the "Make Assembly COM-Visible" and "Register for COM Interop" checkboxes were both set. (They're in panels underneath Project -> Properties)
  • Made sure that signing of the DLL was turned off.
  • Messed with IE 7 security settings for Local intranet. I ended up "enabling" pretty much everything that was disabled ActiveX-wise, but I suspect I changed more than I needed to.
Reply | Email | Delete | Modify | 
Re: Re: Running example on a different web server than IIS by Jared On September 10, 2007

I can't believe somebody responded to this so long after the post with exactly the information I was looking for...I just saw this post last week and was disappointed that that nobody had responded to the tomcat question.

I made the change to web.xml and it worked great.  Thanks a ton, you saved me hours and hours.

Reply | Email | Delete | Modify | 
Re: Re: Re: Running example on a different web server than IIS by luis On December 16, 2008

i'm sorry i don't speak english very well, i'm from chile...

When do i find Web.xml file?

could you help me please?

i writing the next code for validation:

<script language="javascript">
      function doScript()
       {
        myControl1.UserText = frm.txt.value;

        alert(myControl1.UserText);
       }
</script>

but, the messege is "undefined" and the object in the page run es only a textbox big.

please, i need your help.

thank

Luis

 

Reply | Email | Delete | Modify | 
Re: Re: Re: Re: Running example on a different web server than IIS by luis On December 16, 2008
i'm use visual studio 2005 and framework v2.0.50727
Reply | Email | Delete | Modify | 
Re: Re: Re: Re: Re: Running example on a different web server than IIS by Andrew On February 1, 2009
In 2005/2008.... rather than the "Register for Com Interop" which is on the Build tab, you need to tick the "Make assembly COM-Visible" option, which is found on the Assembly Info dialog, accessed by clicking "Assembly Information..." button on the  Application tab.... I ticked this and the "undefined" error went away!
Reply | Email | Delete | Modify | 
Re: Re: Running example on a different web server than IIS by Shellie On January 7, 2008

Thanks David for a great example!

Christopher thanks for the tips on Tomcat! 

 

This also applies to Oracle 10g application server and C++ ActiveX control.

 

Reply | Email | Delete | Modify | 
Re: Re: Re: Running example on a different web server than IIS by Megha On January 28, 2008

I have tried hosting the control in tomcat server and it works fine.

But when I tried to load a windows control that references another windows control, it does not work.

For instance, I have a windows control (Ctrl1) and windows control (Ctrl2). Ctrl1 references Ctrl2 and instantiates it.

Do I have to do anything extra for the referenced assembly?

Can someone please help me with this.

 

Megha.

Reply | Email | Delete | Modify | 
Writing Activex Control by Francisco On March 22, 2006

I wonder if you have any information on how I can intercepet, from a html page, an event raised by the webcontrol. I used to develop activex componentes in Delphi and VB, and this process was pretty simple.  But I am having problems to find information about it in both C# and VB 2005.

I thank you in foward for your help.

Regards, Francisco E Alves

fealves.symetrix@hotmail.com

Reply | Email | Delete | Modify | 
ActiveX in .NET by Alex On October 24, 2006
Can I use these "ActiveX" in ASP ?
Thanks
Reply | Email | Delete | Modify | 
Problem width cache by Cesare On December 29, 2006

Ok. Example run correctly. But if i modify source code the dll not change.  I think because to the first run the dll is cached. Yes but where ?. How I can change dll when I change source code and i rebuild ?. I use IE 7.0.    Thanks

Reply | Email | Delete | Modify | 
Re: Problem width cache by Mike On January 25, 2007
clear the gac cache: VS2005 command window> gacutil /cdl
Reply | Email | Delete | Modify | 
Working in .NET 2.0? by Mike On January 25, 2007
Has anyone got this working in .NET 2.0? All I get in the browser is a textbox html control displayed where the ActiveX control should be.
Reply | Email | Delete | Modify | 
Working in .NET 2.0? by Mike On January 25, 2007
Has anyone got this working in .NET 2.0? All I get in the browser is a textbox html control displayed where the ActiveX control should be.
Reply | Email | Delete | Modify | 
Re: Working in .NET 2.0? by prinju On February 8, 2007
yes u can diplay the activeX control if you copy the dll to the same folder as your html but i am not getting any text displayed in the ActiveX if i click, maybe i did something wrong, lemme chk...
Reply | Email | Delete | Modify | 
Re: Re: Working in .NET 2.0? by Prangya On February 13, 2007
plz tell me if that work. even i am facing the same problem
Reply | Email | Delete | Modify | 
Re: Working in .NET 2.0? by Amel On April 10, 2007

I have gotten this to work in C# and in VB.net,.NET 2.0, this guy this a great job with his example. 

Reply | Email | Delete | Modify | 
Re: Re: Working in .NET 2.0? by Amel On April 16, 2007
Reply | Email | Delete | Modify | 
Re: Re: Working in .NET 2.0? by Byron On June 1, 2007
Amel, Can you tell us what you did to get this to work? Like many others, I am unable to get the text to actually update in the user control. I can see the user control, but when I call the public property... nothing. Did you have to strong name the control, gac it, etc, as others have mentioned. Please specify what you did to get this to work in .Net 2.0. Thanks
Reply | Email | Delete | Modify | 
Re: Re: Re: Working in .NET 2.0? by Amel On June 2, 2007

Okay guys there are only a few things that you have to make sure are set for this control to work. Number one and the most common problem is that people take out the code and make their own control and wonder why it doesn't work, (they get it to show up and it doesn't change the text, most common problem), to solve this make sure in the project properties you check mark the Make COM events available option. Also when creating the virtual directory make sure that in the properties you set it to Scripts Only, Not scripts and exec. Also make sure if you control doesn't show at all that you have the path correct to the control in the provided HTML file, the path has to match in order for it to work.  Also clear the GAC sometimes because it can all get bogged down. Another issue people tell me about is if they try to Open (from the virtual directory) the HTML file the control doesn't show up, it won't you have to right click and hit Browse on the HTML file because the paths are different when you hit Open as oppose to Browse, and the path has to match the one in the HTML file otherwise it won't know where the control is located. Good luck with the rest, just remeber if you writting this in Net 2.0+ and doing it C#.net or VB.net it has to work because I got it to work it just might take some tinkering.

P.S. I don't think this works for framework 1, it has to be run in framework 2 or higher. I'm sorry i had to take my email address down because i was getting to many questions and I couldn't keep up.

Reply | Email | Delete | Modify | 
Re: Re: Re: Re: Working in .NET 2.0? by adam On June 21, 2007

 I am having an issue with embedding a windows form control in IE.  On my development pc (xp sp2 IE7) the control loads fine.  I move the site to a web server running server 2003 and the control does not show, I only get the red 'X'.  I have changed the classid to reference the dll on the webserver.  I added the a new code group in .net config and made sure the the url was correct.  I believe all the IIS settings to be correct, it is running only as script and the dll has access.  I can only figure that the dll is not being downloaded so maybe an IIS config I am missing?  Any thoughts??

Thanks in advance!!

Adam

Reply | Email | Delete | Modify |