Load a file into the application that's associated with the files extension.

published 24.July.2008

Introduction

It is a very useful feature to be able to load an external file with the application that is associated with it's extension, from within your Visual Basic code. For example a lot of my applications create HTML files as reports, and then launches the application associated with HTML files to present the report to the user. This could either be IE, FireFox or any other browser the user has installed as their default browser. Similarly I sometimes create CSV files with results data from my applications, and have the system launch their default spreadsheet program so they can process the results further.

So as you can see it's quite a useful feature and very easy to implement with two windows API calls.

Windows API Functions

Copy the block of code below into your application code, so you can reference the two API functions ShellExecute and GetDesktopWindow.

Const SW_SHOWNORMAL = 1

Private Declare Function ShellExecute Lib "shell32.dll" Alias _
    "ShellExecuteA" (ByVal hwnd As Long, ByVal lpszOp As String, _
    ByVal lpszFile As String, ByVal lpszParams As String, _
    ByVal lpszDir As String, ByVal FsShowCmd As Long) As Long

Private Declare Function GetDesktopWindow Lib "user32" () As Long

Create an Open File With Associated Application Function

Next you need to create a function that accepts one string parameter which is the filename you wish to open with it's associated application.

Private Function OpenFileWithAssociatedApp(strFileName As String) As Long
Dim lng_Screen_hDC As Long

    lng_Screen_hDC = GetDesktopWindow()
    OpenFileWithAssociatedApp = ShellExecute(lng_Screen_hDC, _
        "Open", strFileName, "", "C:\", SW_SHOWNORMAL)
End Function

Sample Usage

Below is a code snippet which demonstrates how to call the OpenFileWithAssociatedApp function. The snippet creates a file called report.html in the same folder as the application is running in, it outputs two lines before closing the file. We then pass the filename to the OpenFileWithAssociatedApp function, so that it can be opened in the default browser.

Open App.Path & "\report.html" For Output As #1

    Print #1, "<h1>Report Title</h1>"
    Print #1, "<p>Report content</p>"

Close #1

OpenFileWithAssociatedApp App.Path & "\report.html"

What Next?

Bookmark this article at :-

 

 

About Author:
I'm a father, husband, and a software developer who works for the NHS.
more »

Sections :
« Articles
« Contact


 

TIFF Splitter - A windows utility to split multipage TIFF files into single pages.