Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | 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
Ads by Lake Quincy Media
 Resources  
Close
 Our Network  
Close
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 VB.

Author Rank:
Total page views :  4514
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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 were 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 could 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 VB 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

    Implements ILauncher

 

    Public Sub Run(ByVal name As String, ByVal [date] As String)

        Dim commandString As String

        commandString = String.Format("/N {0} /D {1}", name, [date])

        Process.Start("C:\Program Files\Microgold\Apps\MyApp.exe", commandString)

    End Sub

 

End Class

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)> _

    Sub Run(ByVal name As String, ByVal [date] As String)

End Interface

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

Imports System

Imports System.Collections.Generic

Imports System.Text

Imports System.Windows.Forms

Imports System.Diagnostics

Imports System.Runtime.InteropServices

Namespace HyperLinkLauncher

    <Guid("D1E4C49A-FA4B-424a-8D61-0F5CE8B6F2FB")> _

    <InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _

    Public Interface ILauncher

        <DispId(1)> _

        Sub Run(ByVal name As String, ByVal [date] As String)

    End Interface

    <ProgId("HyperLinkLauncher.Launcher")> _

    <ClassInterface(ClassInterfaceType.None)> _

    Public Class Launcher

        Implements ILauncher

        Public Sub Run(ByVal name As String, ByVal [date] As String)

            Dim commandString As String

            commandString = String.Format("/N {0} /D {1}", name, [date])

            Process.Start("C:\Program Files\Microgold\Apps\MyApp.exe", commandString)

        End Sub

    End Class

End Namespace

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 VB DotnetHeaven.

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# Corner (http://www.c-sharpcorner.com/).


Login to add your contents and source code to 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.
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.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
hi how r u by SABOOR On September 20, 2009
how to make yahoo password hacker . plz help me i m no use bad working
i m only 1 time 
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.