1

我正在 vb.net 中创建一个程序,并且我想将我的应用程序设置为给定文件扩展名的默认应用程序 - 例如,.txt.

我怎样才能做到这一点?

4

2 回答 2

6

这种事情通常由专门的安装程序处理,但你可以使用.net代码来完成,尽管你的程序在运行时需要管理员权限......

在 VB.NET 中查看这个完整的示例:

http://www.devx.com/vb2themax/Tip/19554?type=kbArticle&trk=MSCP

感谢 Marco Bellinaso 的代码。这是防止链接腐烂的逐字代码:

<System.Runtime.InteropServices.DllImport("shell32.dll")> Shared Sub _
    SHChangeNotify(ByVal wEventId As Integer, ByVal uFlags As Integer, _
    ByVal dwItem1 As Integer, ByVal dwItem2 As Integer)
End Sub


' Create the new file association
'
' Extension is the extension to be registered (eg ".cad"
' ClassName is the name of the associated class (eg "CADDoc")
' Description is the textual description (eg "CAD Document"
' ExeProgram is the app that manages that extension (eg "c:\Cad\MyCad.exe")

Function CreateFileAssociation(ByVal extension As String, _
    ByVal className As String, ByVal description As String, _
    ByVal exeProgram As String) As Boolean
    Const SHCNE_ASSOCCHANGED = &H8000000
    Const SHCNF_IDLIST = 0

    ' ensure that there is a leading dot
    If extension.Substring(0, 1) <> "." Then
        extension = "." & extension
    End If

    Dim key1, key2, key3 As Microsoft.Win32.RegistryKey
    Try
        ' create a value for this key that contains the classname
        key1 = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(extension)
        key1.SetValue("", className)
        ' create a new key for the Class name
        key2 = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(className)
        key2.SetValue("", description)
        ' associate the program to open the files with this extension
        key3 = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(className & _
            "\Shell\Open\Command")
        key3.SetValue("", exeProgram & " ""%1""")
    Catch e As Exception
        Return False
    Finally
        If Not key1 Is Nothing Then key1.Close()
        If Not key2 Is Nothing Then key2.Close()
        If Not key3 Is Nothing Then key3.Close()
    End Try

    ' notify Windows that file associations have changed
    SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0)
    Return True
End Function
于 2013-06-19T08:59:02.030 回答
0

我找到了一种通过 vb.net 关联文件的简单方法(来自 CodeProject,链接: http: //www.codeproject.com/Articles/18594/File-Association-in-VB-NET

代码是:

My.Computer.Registry.ClassesRoot.CreateSubKey(".rtf").SetValue("", "Rich Text File", Microsoft.Win32.RegistryValueKind.String)
    My.Computer.Registry.ClassesRoot.CreateSubKey("Rich Text File\shell\open\command").SetValue("", Application.ExecutablePath & " ""%l"" ", Microsoft.Win32.RegistryValueKind.String)
于 2013-06-20T10:45:25.117 回答