我有这样一段代码工作得很好,给我的路径用户的开始菜单:

    Dim oShell As Object = CreateObject("Shell.Application")
    MsgBox(oShell.NameSpace(11).Self.Path)

此显然使用后期绑定。现在说我要做到这一点在C#中,或者两者都不在VB.NET严格模式支持这种语法与后期绑定。

这是可能的?怎么样?

感谢您帮助!

有帮助吗?

解决方案

如果你想解决你要搞清楚这个COM方式,在您的VB项目中添加该COM引用。

打开注册表并导航到HKEY_CLASSES_ROOT\<class id>\CLSID,即

HKEY_CLASSES_ROOT\Shell.Application\CLSID

和你会发现类ID唯一地标识COM组件。

HKEY_CLASSES_ROOT\CLSID你现在可以查找哪个文件是COM组件后面:

HKEY_CLASSES_ROOT\CLSID\{13709620-C279-11CE-A49E-444553540000}\InProcServer32

示出以下值:

%SystemRoot%\system32\SHELL32.dll

现在去到Visual Studio,并添加引用此文件(在浏览的的的添加引用的选项卡的对话)。如果你打开项目的属性,你会真正看到添加的COM组件的好听的名字是微软壳牌控制和自动化

一旦参考加入可以使用Shell.Application对象如下:

Option Strict On

Module PrintStartMenuLocation

    Sub Main()
        Dim shell As New Shell32.Shell
        Dim folder As Shell32.Folder
        Dim folderItem As Shell32.FolderItem
        Dim startMenuPath As String

        folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfSTARTMENU)
        folderItem = CType(folder.Items(0), Shell32.FolderItem)
        startMenuPath = folderItem.Path

        Console.WriteLine(startMenuPath)
    End Sub

End Module

在C#一个版本将如下所示:

class Program
{
    static void Main(string[] args)
    {
        Shell32.Shell shell = new Shell32.Shell();
        Shell32.Folder folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfSTARTMENU);
        Shell32.FolderItem folderItem = folder.Items().Item(0) as Shell32.FolderItem;
        string startMenuPath = folderItem.Path;

        Console.WriteLine(startMenuPath);
    }
}

不过,如果你只是需要找回开始菜单文件夹的位置,你可以直接在.NET中使用做同样的

Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)

其他提示

那么实际上你可以使用反射:

Type shellType = Type.GetTypeFromProgID("Shell.Application", true);
object shell = Activator.CreateInstance(shellType);
object folder = shellType.InvokeMember("NameSpace", BindingFlags.InvokeMethod, null, shell, new object[] { 11 });
object self = folder.GetType().InvokeMember("Self", BindingFlags.GetProperty, null, folder, new object[] { });
object path = self.GetType().InvokeMember("Path", BindingFlags.GetProperty, null, self, new object[] { });
Console.WriteLine(path);

不是那种代码,我喜欢,但在C#4.0中,你可以使用的动态类型来清理这种混乱。

Dim DirPath As String = _
    System.Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)

请参阅此处更多。

如果我没有记错,你所要做的就是为对象引用浇铸成相应的接口。如果在.NET使用COM对象时,通常导入类型库,然后让接口容易获得的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top