Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » COM Interop » Using a COM Callable Wrapper to Launch a Program from a Hyperlink in the WebBrowser Control

Using a COM Callable Wrapper to Launch a Program from a Hyperlink in the WebBrowser Control

This article describes how you can launch an application from a link inside the WebBrowser Control using a combination of javascript and an ActiveX Control created in C#.

Author Rank :
Page Views : 55549
Downloads : 0
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

One of the big challenges I had to overcome this week was how to launch an application with arguements from a hyperlink in the WebBrowser Control.  You would think this would be fairly easy, but underneath the workings of the WebBrowser Control is security-heavy Internet Explorer.  I guess one of Microsoft's ongoing challenges is to balance the amount of security  IE needs against viruses and wormbots and to make the control useable for developers. It seems to me, when it comes to automating IE,  Microsoft has lately been leaning on making life more secure for the consumer and more painful for developers.  I guess my mistake was to think I could use the WebBrowser Control as a Reporting Tool and extend it beyond simple reporting.  Still, it would be REALLY nice if there was a way to turn off the security for the WebBrowser control when you are developing it to be used as an application on a local machine.

Anyway, after three days of research and some hard learning experience, I managed to figure out how you could launch an application from a hyperlink in HTML.  The trick is to write javascript into your HTML report that will create an ActiveX control that will in turn call the application you wish to launch.

Figure 1 - Steps for running an executable from a hyperlink in IE

Javascript from a Hyperlink

Did you know that you can launch javascript from a hyperlink using the following syntax?

<a href = "javascript:alert('hello')"> post alert</a>

You can try it yourself by just typing

 javascript:alert('hello')

into your browser, which brings up figure 2:

Figure 2 - Result of javascript command in browser edit window

The same technique can be used to call your own javascript function called launch, that will eventually launch your local machine process:

<a href = "javascript:launch('name', 'date')">launch it!</a>

In my current project, I needed to generate the line above for a report using xsl. If you are generating the hyperlink above from xsl,  your xslt for this might look like the following (xsl gives you the flexibility of populating the parameters in your javascript call with data from an xml file.)

Listing 1 - XSL for generating a hyperlink that calls javascript

<A>
<xsl:attribute name="HREF">
javascript:launch('<xsl:value-of select ="$name"/>', '<xsl:value-of select ="$date"/>')
</xsl:attribute>
<xsl:value-of select ="$title"/>
</A>

So what does the javascript launch code look like?  The javascript just gives us a conduit to an ActiveX control which we can call with the parameters name and date.  We simply use the javascript to create the ActiveX COM object and dispatch a Run call from the object.

Listing 2 - javascript for creating and calling an ActiveX Object

<script type="text/javascript">
function launch(name, date)
{
  var myLauncher = new ActiveXObject('HyperLinkLauncher.Launcher');
  alert ("name:" + name + " date:" + date);
  myLauncher.Run(name, date);
}
</script>

If we want to include the javascript in our xsl generation script, we can just stick the javascript all in a CDATA block so xsl won't get confused by the javascript symbols and characters:

Listing 3 - xsl for generating the javascript in listing 2

 <script type="text/javascript">
<![CDATA[
function launch(name, date)
{
  var myLauncher = new ActiveXObject('HyperLinkLauncher.Launcher');
  alert ("name:" + name + " date:" + date);
  myLauncher.Run(name, date);
}
]]>
</script>

Creating an COM Callable Wrapper (CCW) in .NET

Now we have all the pieces in our HTML to call an ActiveX Control with parameters from HTML.  The next step is to create the ActiveX control that will launch a process on our local machine.  Microsoft gives us an easy way to create ActiveX controls in .NET using the COM Callable Wrapper.  By just placing a few attributes in our classes and interfaces, we can add automation directly into a .NET program or library. (It sure beats the old way using ATL!!)

So let's review what we are trying to do.  We are trying to launch a process from the hyperlink and pass it parameters.  In order to launch the process we need to create an ActiveX Control called HyperLinkLauncher.Launcher.  The first step to creating are ActiveX COM callable wrapper is just to create a new project of type library.  ActiveX controls don't need to be executables, we just need to be able to create them and use their an interface to access their methods and properties.  Go to the File->New->Project menu and choose a Class Library project as shown in figure 2.

Figure 2 - Creating a C# Project of Type Library

Next we open up the Launcher class and add a ProgId attribute to the class named "HyperLinkLauncher.Launcher".  Adding this attribute will allow us to create a COM object with this name using javascript.  Also we want to add a Run method to run our command line application.  The Run method uses the System.Diagnostics.Process.Start method to launch our commandline process with the name and date parameters.

Listing 4 - Adding the ProgId attribute

    [ProgId("HyperLinkLauncher.Launcher")]
    [ClassInterface(ClassInterfaceType.None)]
    public class Launcher : ILauncher
    {

      public void Run(string name, string date)
        {
            string commandString;
            commandString = string.Format("/N {0} /D {1}", name, date);
            Process.Start(@"C:\Program Files\Microgold\Apps\MyApp.exe",
                                                 commandString);
        }

    }

In order to access our run method through COM, we need to add an interface.  This interface will be used to create our dispatch interface which will expose our COM methods and properties.  The interface is shown in listing 5.  The InterfaceType attribute and the DispID attribute adds the plumbing  to create the necessary COM functionality:  Also you need a GUID (unique id) attribute, to distinguish your ActiveX controls from all the other activex controls on your computer system.  You can generate the GUID from the VS.NET menu under Tools->Create GUID and then paste the GUID into the Guid attribute above your interface.

Listing 5 - Adding the ProgId attribute

    [Guid("D1E4C49A-FA4B-424a-8D61-0F5CE8B6F2FB")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface ILauncher
    {
        [DispId(1)]
        void Run(string name, string date);
    }

The full code for your the CCW is shown in Listing 6.  Note that there really isn't that much coding necessary to turn your .NET class into a COM object.

Listing 6- A COM Callable Wrapper for Launching a Process with Arguements

using System;
using
System.Collections.Generic;
using
System.Text;
using
System.Windows.Forms;
using
System.Diagnostics;
using
System.Runtime.InteropServices;

namespace HyperLinkLauncher
{

    [Guid("D1E4C49A-FA4B-424a-8D61-0F5CE8B6F2FB")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface ILauncher
    {
        [DispId(1)]
        void Run(string name, string date);
    }

    [ProgId("HyperLinkLauncher.Launcher")]
    [ClassInterface(ClassInterfaceType.None)]
    public class Launcher : ILauncher
    {
        public void Run(string name, string date)
        {
            string commandString;
            commandString = string.Format("/N {0} /D {1}", name, date);
            Process.Start(@"C:\Program Files\Microgold\Apps\MyApp.exe",
                                                 commandString);
        }

    } 

}

Installing the COM Callable Wrapper

It's not enough to build the CCW and celebrate your successful hack.  In order to get your COM callable wrapper to work properly,  three things need to happen (1) Your CCW must be strong named  (2)  you need put your library assembly into the GAC.  (3)  You need to register your Active X control as a COM object.

In order to create a strong name for your assembly, go to your project properties in Visual Studio, pick the signing tab, and check Sign the assembly.  Also, you will need to provide a strong name key file name.

 

Now we need to place the signed assembly in the GAC.  The easiest way to stick the CCW into the GAC is to open up c:\windows\assembly under file explorer and drag your compiled dll into the directory.  Of course, you could also use the command line tool gacutil.exe.

    gacutil.exe /i  Launcher.dll

To register your COM callable wrapper with your system,  you'll need to use regasm  (regsvr32.exe won't work on a .NET CCW).  Upon running regasm, the utility will indicate if your dll was registered successfully.  You can also use visual studio 6.0 tools such as OLE View to look at the contents of Launcher.tlb after it is generated to make sure that your COM interface was created properly.  The command line for regasm is (including type lib generation) is shown below:

regasm /tlb:Launcher.tlb Launcher.dll

Once you've successfully registered your COM object, you can test your javascript code to make sure it launches your app properly.  You may want to add a MessageBox.Show (you'll need to include System.Windows.Forms.dll in your library references.)  in your Run method to make sure your ActiveX Run command is being accessed.

Conclusion

Creating COM callable objects is a snap using the attributes provided with the .NET framework.  One of the great uses for these CCW's (along with javascript) is to allow you to launch applications from the WebBrowser control.  Unfortunately, you will still initially see the warning in the WebBrowser control that says,  "An active x control might be unsafe...".  I have not yet figured out how to get rid of this annoying message.  If you have any suggestions, feel free to contact me and I'll add it to this article.  Fortunately, the message disappears once you say Yes, but will come back next time you run the application.

Figure 3 - Warning that comes up in the WebBrowser Control

Anyway,  hopes this help you utilize the WebBrowser control as a more interactive part of your .NET arsenal.  Remember, if you have any COMments, please feel free to share them here on C# Corner.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate 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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
solution to warning message by eberirigoyen On March 2, 2007
- Add the site to the trusted sites - Internet Explorer menu Tools, Internet Options, Security, Trusted Sites, Custom Level, Enable: - Download unsigned ActiveX controls - Initialize and script ActiveX controls not marked as safe for scripting depending on your particular settings you might need to enable other things there
Reply | Email | Modify 
Re: solution to warning message by Mike On March 8, 2007
that's a start.  Is there anyway programmatically to add the control as a trusted component by running something on the client side?
Reply | Email | Modify 
RegAsm error by sasha On March 15, 2007

Hello Mike, I'm C# newbie. I like your article (sample) very much. I followed every step from the sample and I was able to build the DLL. I also implemented a javascript call to the DLL into a sample HTML page. I have two problems, first: I'm getting RegAsm error: Failed to load 'C:\Launcher.dll' because it is not a valid .NET assembly., and second, if I try to look at the DLL via the OLE viewer I'm getting another error: TYPE_E_CANTLOADLIBRARY. Any help would be very appreciated.

(Modified:03/16/2007)

BTW,  I tested the Launcher.dll, by calling the Run function from inside the dll (plus I triggered a message box 'Hello from inside the DLL' succesfuly); however I did this from another C# application. I would like to do the same from an HTML page.

(Modified:03/17/2007)

Got it, Mike. I finally registered the assembly. I had to copy my dll inside the folder "drive:\Program files\Microsoft Visual Studio .Net\VC#" and run RegAsm.exe, and finaly it registered the CCW (dll). After that I succesfuly run my exe that was written in Visual DataFlex by calling the Run function from an HTML page via javascript. Cool example (article). Thank you.

 

 

Reply | Email | Modify 
Re: RegAsm error by Mike On April 6, 2007
Glad you got it working!

-Mike

Reply | Email | Modify 
Re: Re: RegAsm error by Loukil On April 19, 2007

Please I Want to Use your solution to launch the calculator or Outlook , I'am not very experiment on C# can you help me please.

when I Tried To Test your example I had this JavaScript Error :

Can't create ActiveX Composant

 

Reply | Email | Modify 
Automation Server Can't create object by jayashree On April 4, 2007
Reply | Email | Modify 
Online tool that will generate personalized documents on-fly – will involve online image resize and crop tool and template selection. by Njck On May 9, 2007
Project description: Online tool that will generate personalized documents on-fly – will involve online image resize and crop tool and template selection. Functionality: Module 1: users will upload an image. They will be able to select/crop an image area (using an online image crop toll similar with 12CropImage 2 Beta (http://roel.meurders.nl/web_php/12cropimage-php-image-crop/) or http://mypictr.com/). On the same webpage, the users will select a predefined template. Module 2: We need an engine that will be able to pass the image (image name, path, etc.) and the template name (file name) as variables (parameters) to another application (i.e. MS Word, Adobe Photoshop, or any other DTP application). We are able to create an offline batch process using WinTask. The WinTask batch launch the application.exe, opens the template, place the image, save the new file as “image name” and close the template. We need the same process on-fly. Module 3: The new file is available for download. Is this possible? What will be total time and cost estimate to complete this project? Thanks, Nick B
Reply | Email | Modify 
Automation Server Can't create object by Ron On July 10, 2007
Hi Mike...this is just what I have been looking for. I have tried several other approaches to no avail but this one looks promissing. I followed everything step by step and everything registered and all with no problems. Now I am trying to run it and I get a javascript error on the page when I click on the link. It says, "Automation Sercer can't create object". This is the only object on the page. Any ideas? Thanks...Ron
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.