美文网首页
在Win10上用代码方式创建ShortCut

在Win10上用代码方式创建ShortCut

作者: 黑山老雕 | 来源:发表于2019-09-29 10:24 被阅读0次

之前,创建快捷方式使用的是WshShell,后来发现这种方法如果路径中有中文的话是不支持的。应该用Shell对象。
···
public static void CreateShortcutShell32(string ShortcutName, string targetPath, string shortcutPath, string iconLocation = null, string description = "", string arguments = "")
{
if (!Directory.Exists(shortcutPath))
{
Directory.CreateDirectory(shortcutPath);
}

        string shortcutFullPath = Path.Combine(shortcutPath, $"{ShortcutName}.lnk");

        // Create empty .lnk file
        System.IO.File.WriteAllBytes(shortcutFullPath, new byte[0]);
        // Create a ShellLinkObject that references the .lnk file
        //Shell32.Shell shell = new Shell32.Shell(); // This doesn't work on Win10
        Shell32.Folder dir = GetShell32Folder(shortcutPath);
        Shell32.FolderItem item = dir.Items().Item($"{ShortcutName}.lnk");
        Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)item.GetLink;
        // Set the .lnk file properties
        lnk.Path = targetPath;
        lnk.Description = description;
        lnk.Arguments = arguments;
        lnk.WorkingDirectory = Path.GetDirectoryName(targetPath);
        lnk.SetIconLocation(string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation, 0);
        lnk.Save(shortcutFullPath);
    }

···
注意 Shell32.Shell shell = new Shell32.Shell(); 的方式在Win10上不能用,需要用反射的方式来获取Shell32.Folder对象

        private static Shell32.Folder GetShell32Folder(string folderPath)
        {
            Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
            Object shell = Activator.CreateInstance(shellAppType);
            return (Shell32.Folder)shellAppType.InvokeMember("NameSpace",
            System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { folderPath });
        }

同时,因为不能直接创建lnk,所以先创建一个空白的,然后修改各项属性。
参考:
https://stackoverflow.com/a/19035049/5793480

转载请注明出处。如果您觉得本文有用,欢迎点赞。
更多教程请在网易云课堂B站优酷腾讯视频搜索黑山老雕。

相关文章

网友评论

      本文标题:在Win10上用代码方式创建ShortCut

      本文链接:https://www.haomeiwen.com/subject/qtpoectx.html