![]() |
|
|
Lounge |
Languages »
VB.NET »
General
Intermediate
License: The Common Development and Distribution License (CDDL)
File Association in VB.NETBy Nickr5Easily associate your programs with file types (.jpg, .html, .mp3) with just 2 lines of Visual Basic code. |
VB 8.0, VB 9.0, VBWindows, .NET, .NET 3.0, .NET 2.0, WinXP, Vista, WinForms, VS2005, Visual Studio, Dev
|
||||||||||||
|
Advanced Search Sitemap |
|
|
|
||||||||||||||||
There are many features that every commercial application has, but aren't easy to implement, or find out how to implement, for many people.
Look at Undo/Redo, the Office 2007 Ribbon Bar, spell check, associated file types, and lot's of other small, but powerful features.
While many of these aren't actually hard to program, it can be difficult to find out exactly how. More specifically, this article is on how to link a file extension
(or two, three, four, or five...) to your program and have your application display the appropriate content according to the file.
Take a second to open up Windows Explorer. See all the different types of files (jpg, gif, png, txt, html, etc)? Each one has a different icon and opens with
a certain application when you double click on it. Take a guess, how many lines of code does it take to link your application and an extension? 10? 20? 30?
The answer is 2. Just 2 will do it!
The registry stores all the file type-app associations. Click on the Start Menu > Run > Type in 'regedit' > Ok.
Now expand the HKEY_CLASSES_ROOT node. At the top of the window are all the extensions that your computer recognizes. Scroll down to .txt and click on it.
Now look at the default value, it probably is 'txtfile'. Scrolling down the tree on the left, find the txtfile node. This contains all the information about
any extensions that have their default value set to txtfile. Right now, we're just interested in opening the file, so open Shell > Open > Command.
If your .txt files open with notepad, then the default value should be "%SystemRoot%\system32\NOTEPAD.EXE %1".%SystemRoot% is pretty self-explanatory, it's replaced by the folder that contains system32, which contains NOTEPAD.EXE.%1 is a command-line argument to pass the the program when a txtfile is opened. %1 is replaced by the file's location.
The first step is to get your application to open when a chosen extension (like .mp3) is double clicked in Windows Explorer.
For this article, we'll use a file extension that shouldn't exist: .Hello. To use this file type, create a new project called 'Hello World'.
The basic idea is this: a .Hello file contains (in plain text) an adjective. When one is opened, a message box will pop-up and say, "Hello, (file contents) World".
If you open the application manually, it will just say, "Hello, World".
Now we have to edit the registry just like you saw with the .txt extension. In the forms Load event, type the following:
My.Computer.Registry.ClassesRoot.CreateSubKey(".Hello").SetValue("", "Hello", Microsoft.Win32.RegistryValueKind.String)
My.Computer.Registry.ClassesRoot.CreateSubKey("Hello\shell\open\command").SetValue("", Application.ExecutablePath & _
" ""%l"" ", Microsoft.Win32.RegistryValueKind.String)
What does all this do? If you don't understand My.Computer.Registry, here's a link to it on MSDN, otherwise look below:
|
Code |
What it does |
|---|---|
CreateSubKey(".Hello") |
Creates a registry key in ClassesRoot for the .Hello extension. Notice that you must include the beginning period. |
.SetValue("", "Hello"... |
|
CreateSubKey("Hello" & _ "\shell\open\command") |
This creates the " |
.SetValue("", Application.ExecutablePath & _ " ""%l"" ",... |
|
Now run your application once. It will edit the registry. Your program is now associated with the .Hello file!
You want to create file association for .txt in your program. You create the file association, but it still opens in Notepad.What's going on? There is another value that needs to be deleted located here:HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.txtThe value name is 'Progid'. This will consist of a string value of the default program to open this filetype. If this value is present,you will not be able to associate anything with this particular filetype. You must delete the 'Progid' value in order for the association to work.Thanks, Computer Masster!
Now to test it out. Open Notepad, type in an adjective, and save it as a .Hello file (Make sure you don't accidentally save it as a .Hello.txt file).
Open the file in Windows Explorer. Your program will run! But nothing happens...
Now I've told you how to associate the files and the article should be over, right? Nope! This wouldn't be any use if you didn't know how to read the
command-line arguments and finish the program! Luckily, this is simple. My.Application.CommandlineArgs returns a ReadonlyCollection(Of String).
When the registry is set correctly and a file is opened in Windows Explorer, the file's path is pass as a command-line argument
(if you think of an application as a method - a subroutine or function - then these are the parameters).
To retrieve the arguments, you useMy.Application.CommandlineArgs. It returns aReadOnlyCollection(Of String).
You can useMy.Application.CommandlineArgs(0)to retrieve the file path, or use the code below to convert the collection to an array.
To convert this to an array (which you don't really need to do unless you're not familiar with working with collecions),
add the following to the Application's Load Event:
'Array to hold the arguments
Dim strAllArgs(My.Application.CommandLineArgs.Count - 1) As String
'Counter Variable
Dim x as integer = 0
For Each arg as string In My.Application.CommandLineArgs
'Write the arguments to an array
Try
strAllArgs(x) = arg
'Catch Exceptions
Catch ex As Exception
strAllArgs(x) = "Could not write argument."
Debug.Writeline(ex.message)
End Try
x += 1
Next
If My.Application.CommandLineArgs.Count = 0 Then
ReDim strAllArgs(0) As String
strAllArgs(0) = Nothing
End If
The strAllArgs is the new array.
Now, we have to display the message. More code for the Load event:
msgbox("Hello, " & My.Computer.FileSystem.ReadAllText(strAllArgs(0)) & " World!")
(The easier way)
Okay, now you've done it the hard way, time to learn the easy way. Using the included RegistryActions DLL,
you can associate a file type with a variable and a method. Then, you can read the arguments with just one more method!
Imports RegistryActions.FileAssociation
Public Class HelloForm
Private ftHello As New FileType(".Hello", "Hello", "Hello World Adjective File", "C:\World.ico")
Private Sub HelloForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DoAssociation.Associate(ftHello, Application.ExecutablePath)
msgbox("Hello, " & My.Computer.FileSystem.ReadAllText(DoAssociation.WriteCommandsToArray(My.Application.CommandLineArgs)(0)) & " World!")
End Sub
End Class
See the documentation for more on the RegistryActions Namespace.
Explore the HKEY_CLASSES_ROOT hive. Look for additional features you can add, for example when you right click on a file. Find out how to change the default
icon for a file type... And Keep on Programming!
| Date | Change |
|---|---|
| 4/29/07 | Article Submitted |
| 4/30/07 |
|
| 5/8/07 |
|
| 6/3/07 | Added this tip. |
| 6/8/07 | Fixed problems in the DLL. |
| 6/26/07 | Changed the wordings in some phrases and fixed some errors in the examples. |
| 6/29/07 |
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 3 Feb 2009 Editor: |
Copyright 2007 by Nickr5 Everything else Copyright © CodeProject, 1999-2009 Web17 | Advertise on the Code Project |