【问题标题】:Can a global Shortcut .lnk be created programmatically?可以以编程方式创建全局快捷方式 .lnk 吗?
【发布时间】:2015-07-27 20:22:09
【问题描述】:

我目前正在以编程方式创建快捷方式,但我想知道是否可以在 C# 中以类似方式创建全局快捷方式。

下面是我的代码:

WshShell shell = new WshShell();
string shortcutLocation = "pathToShortcut//Shortcut1.lnk"
IWshShortcut shortcut = shell.CreateShortcut(shortcutLocation);
shortcut.Arguments = "foo bar";
shortcut.Description = "Test Shortcut";
shortcut.TargetPath = "pathToShortcutExe";
shortcut.WorkingDirectory = "pathToWorkingDirectory"
shortcut.Save();

这段代码非常适合为用户创建快捷方式,但我想知道是否有一种方法可以为系统执行此操作。我已经看到全局安装的程序会在所有用户上放置快捷方式,所以我很好奇如何在 C# 中实现这种效果。

【问题讨论】:

    标签: c# desktop-shortcut


    【解决方案1】:

    是的,你可以.. 您必须添加一个参考项目 > 添加参考 > COM > Windows 脚本宿主对象模型。

        using IWshRuntimeLibrary;
    
        private void CreateShortcut()
        {
          object shDesktop = (object)"Desktop";
          WshShell shell = new WshShell();
          string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\Notepad.lnk";
          IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
          shortcut.Description = "New shortcut for a Notepad";
          shortcut.Hotkey = "Ctrl+Shift+N";
          shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolders.System) + @"\notepad.exe";
          shortcut.Save();
        }
    

    【讨论】:

    • 您能否详细说明一下 shDesktop 对象是什么?这似乎是您添加的主要区别。 +1
    • 我也很好奇这如何使快捷方式全球化?
    • 它基本上是一个字符串,它的内容是“桌面”,所以我们可以添加对该对象的引用以便能够在 SpecialFolders.Item() 函数中调用它
    • 因为参数必须是一个对象..检查这个网址msdn.microsoft.com/en-us/library/0ea7b5xe(v=vs.84).aspx如果我可以帮助你请接受我的解决方案
    • 我没有接受,因为我还无法验证它是否有效。我已经运行了代码,它在我的桌面上创建了一个记事本快捷方式,但在任何其他用户桌面上都没有。我还查看了您链接的文章,发现您可以将 shell 特殊文件夹交换为其他选项,而我使用了“AllUsersDesktop”,我认为这可能会起作用,但仍然无法验证
    猜你喜欢
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    相关资源
    最近更新 更多