简体   繁体   English

如何在C#中创建相对的Windows快捷方式?

[英]How to create a relative Windows shortcut in C#?

I'm trying to combine two questions here: 1) How to create a relative shortcut in Windows and 2) How to create a Windows shortcut in C# 我在这里尝试合并两个问题:1) 如何在Windows中创建相对快捷方式,以及2) 如何 在C#中 创建 Windows快捷方式

I have the following code to create shortcuts (based on the questions I've seen), but it throws an exception when assigning shortcut.TargetPath : "Value does not fall within the expected range" 我有以下代码创建快捷方式(基于我所看到的问题),但是在分配shortcut.TargetPath时会引发异常。TargetPath:“值不在预期范围内”

public void CreateShortcut() {
    IWshRuntimeLibrary.WshShell wsh = new IWshRuntimeLibrary.WshShell();
    IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(Path.Combine(outputFolder, "sc.lnk")) as IWshRuntimeLibrary.IWshShortcut;
    shortcut.Arguments = "";
    shortcut.TargetPath = "%windir%\\system32\\cmd.exe /c start \"\" \"%CD%\\folder\\executable.exe\"";
    shortcut.WindowStyle = 1;
    shortcut.Description = "executable";
    shortcut.WorkingDirectory = "%CD%";
    shortcut.IconLocation = "";
    shortcut.Save();
}

How do I fix this and create my relative shortcut? 如何解决此问题并创建我的相对快捷方式?

NB: I don't want to have to write a batch script to do this as my software will most likely be installed on PCs where the user does not have access to a command line - our clients often have very locked-down machines and will almost certainly not have the right permissions to run batch files. 注意:我不需要编写批处理脚本来执行此操作,因为我的软件很可能会安装在用户无法访问命令行的PC上-我们的客户通常拥有非常锁定的计算机,并且会几乎可以肯定没有运行批处理文件的正确权限。 If you do have any suggestions as to how I might create a 'portable' folder (with my .exe in a subfolder) where the user only has to double-click something in the top level folder to run the exe, I am open to suggestions! 如果您确实对如何创建“便携式”文件夹(将我的.exe放在子文件夹中)有任何建议,则用户只需双击顶级文件夹中的某些文件即可运行exe,那么我可以打开建议!

You can't put arguments in the TargetPath -property. 您不能将参数放在TargetPath -property中。 (see MSDN ) (请参阅MSDN

Put them into the Arguments - property: 将它们放入Arguments属性:

public void CreateShortcut() {
    IWshRuntimeLibrary.WshShell wsh = new IWshRuntimeLibrary.WshShell();
    IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(Path.Combine(outputFolder, "sc.lnk")) as IWshRuntimeLibrary.IWshShortcut;
    shortcut.Arguments = "/c start \"\" \"%CD%\\folder\\executable.exe\"";
    shortcut.TargetPath = "%windir%\\system32\\cmd.exe";
    shortcut.WindowStyle = 1;
    shortcut.Description = "executable";
    shortcut.WorkingDirectory = "%CD%";
    shortcut.IconLocation = "P:\ath\to\any\icon.ico";
    shortcut.Save();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM