How to create desktop shortcut for msix packaged winui3 project

207 Views Asked by At

That is, after user installing the msix, there should be the shortcut. Or at least, the app create the shortcut after first launch. Not some post-installation script.

I tried desktop7:Shortcut, but the shortcut does not appear.

2

There are 2 best solutions below

0
Junjie Zhu - MSFT On

First of all, the packaged WinUI3 app cannot be started from the exe, so creating a shortcut is invalid, this is by design.

If you need to create a shortcut on the desktop, first you need to make your app non-packaged (unpackaged) and self-contained), you need to modify your csproj file.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    ...
    <WindowsPackageType>None</WindowsPackageType>
    <WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
  </PropertyGroup>

    

Then you can try to create a desktop shortcut with the Windows Script Host.

Project > Add Reference > COM > Windows Script Host Object Model.

using IWshRuntimeLibrary;

[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);
private 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) + @"\yourAppName.lnk";
    IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
    shortcut.Description = "New shortcut for a yourAppName";
    shortcut.Hotkey = "Ctrl+Shift+N";
    shortcut.TargetPath = lpExeName.ToString();
    shortcut.Save();
}
0
Peter Torr On

If this is a full-trust MSIX, you should be able to create a shortcut for it on first-run by using the Shell Folder APIs. To get started, take a look at this repo to see if it can work for you.

If it's a low-trust UWP then there is currently no solution.

Note that once you create the shortcut, there is no way to automatically remove it when the MSIX app is uninstalled; the shortcut will still be there but will just point to nothing.