These two functions allow you to associate a program with a certain file type:
Imports:
Code:
Imports System.Runtime.InteropServices
Main code:
vb Code:
<DllImport("shell32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Private Shared Sub SHChangeNotify(ByVal wEventId As UInt32, ByVal uFlags As UInt32, ByVal dwItem1 As IntPtr, ByVal dwItem2 As IntPtr)
End Sub
Private Const SHCNE_ASSOCCHANGED As UInt32 = &H8000000
Private Const SHCNF_IDLIST As UInt32 = &H0
Public Shared Function Associate(ByVal type As String, ByVal typename As String, ByVal executable As String, Optional ByVal arguments As String = "%1") As Boolean
DeAssociate(type)
Try
My.Computer.Registry.ClassesRoot.CreateSubKey("." & type).SetValue("", typename)
My.Computer.Registry.ClassesRoot.CreateSubKey(typename & "\shell\open\command").SetValue("", executable & " " & arguments)
My.Computer.Registry.ClassesRoot.CreateSubKey(typename & "\DefaultIcon").SetValue("", executable)
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero)
Return True
Catch
Return False
End Try
End Function
Public Shared Function DeAssociate(ByVal type As String) As Boolean
Try
Dim typename As String = My.Computer.Registry.ClassesRoot.OpenSubKey("." & type).GetValue("")
My.Computer.Registry.ClassesRoot.DeleteSubKey("." & type)
My.Computer.Registry.ClassesRoot.DeleteSubKeyTree(typename)
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero)
Return True
Catch
Return False
End Try
End Function
Public Shared Function IsAssociated(ByVal type As String) As Boolean
Try
Dim typename As String = My.Computer.Registry.ClassesRoot.OpenSubKey("." & type, False).GetValue("")
My.Computer.Registry.ClassesRoot.OpenSubKey(typename, False)
Return True
Catch
Return False
End Try
End Function
To associate:
Code:
Associate("type", "Type file", "C:\program files\typeopener.exe", "-i %1"
Associates the file type ".type" to the typeopener.exe program. When opening the file in Windows it will use the "-i %1" arguments, where "%1" is the file opened. The type displayed in the properties dialog will be "Type file".
To de-associate:
Code:
DeAssociate("type")
It will search the type name of "type" (="Type file") and removes both keys and for the type name the entire tree.
To check if a type is associated:
Code:
If IsAssociated("type") Then
MessageBox.Show("Type is associated")
End If
Note that all these functions are not very solid, since they use a Try-Catch block to check if the operation is possible.
You could add checks to existing keys, but looping the GetSubKeyNames function could mean a loss of performance.
SHChangeNotify is used to make Windows update the association internally. (Icons)
For a more advanced class you could use FileAssociation.vb from Mentalis.org.
Special thanks go to Edgemeal.