I have a .net 9 Maui windows application, and need to create a desktop shortcut for it. The code I would normally use for this is:
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();
}
However Shell32 isn't found though. Is there a new way of creating desktop shortcuts when running a maui application?
Further info: Adding "Microsoft Shell Controls and Automation" as a com reference, Shell32.Shell exists, but does not contain the method "CreateShortcut"
You can refer to this official document about How to create a desktop shortcut with the 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();
}
}
}
And then you can new the Helper.cs and call the CreateShortcut() method.