我有一个 .net 9 Maui windows 应用程序,需要为其创建一个桌面快捷方式。 我通常使用的代码是:
public static void CreateDesktopShortcut()
{
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string shortcutPath = Path.Combine(desktopPath, "thing.lnk");
var shell = new Shell32.Shell();
var shortcut = (Shell32.ShellLinkObject)shell.CreateShortcut(shortcutPath);
shortcut.TargetPath = "path.exe";
shortcut.Description = "interesting description";
shortcut.Save();
}
但是没有找到 Shell32。 运行 maui 应用程序时是否有创建桌面快捷方式的新方法?
更多信息: 添加“Microsoft Shell Controls and Automation”作为com引用,Shell32.Shell存在,但不包含方法“CreateShortcut”
您可以参考这个官方文档如何使用Windows Script Host创建桌面快捷方式。
<ItemGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">
<COMReference Include="IWshRuntimeLibrary">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>0</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>f935dc20-1cf0-11d0-adb9-00c04fd58a0b</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
</ItemGroup>
namespace MauiApp.Platforms.Windows
{
public class Helper
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool QueryFullProcessImageName(IntPtr hProcess, uint dwFlags,
[Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpExeName,
ref uint lpdwSize);
public void CreateShortcut()
{
// Get a handle to the current process
IntPtr hProcess = Process.GetCurrentProcess().Handle;
uint dwFlags = 0;
StringBuilder lpExeName = new StringBuilder(260);
uint lpdwSize = (uint)lpExeName.Capacity;
//Get exe path
bool result = QueryFullProcessImageName(hProcess, dwFlags, lpExeName, ref lpdwSize);
object shDesktop = (object)"Desktop";
WshShell shell = new WshShell();
string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\MauiApp.lnk";
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "New shortcut for a MauiApp";
shortcut.Hotkey = "Ctrl+Shift+N";
shortcut.TargetPath = lpExeName.ToString();
shortcut.Save();
}
}
}
然后您可以新建 Helper.cs 并调用 CreateShortcut() 方法。