DotNetSpartan
DotNetSpartan

Reputation: 1001

Win 11 : Pin Unpin a shortcut programmatically using C#

Is there any way in C# to pin/unpin an application to Startmenu and taskbar in Windows 11. I am using .NET Framework 4.8.

I am able to pin/unpin shortcuts to Taskbar and Startmenu locations in Win 10 using the Pin/Unpin API mentioned here

How can I achieve the pin/unpin of shortcuts in Windows 11 using C# ?

Upvotes: 2

Views: 1546

Answers (1)

caesay
caesay

Reputation: 17213

The "unofficial" way (which you linked) to do this has changed a few times already, and Microsoft may keep breaking this to prevent application developers from doing this without user consent. The philosophy is that the application drawer (start menu) is where the user should find your app. If they want it to be more prominent (on the taskbar), it should be via user choice.

In Windows 10 and 11, there is an official API to ask the user to pin your app to the start menu. https://learn.microsoft.com/en-us/windows/apps/design/shell/pin-to-taskbar

To use this you will need to set a windows TFM greater than 10.0.16299.

For example, in your csproj you can set the TFM as follows

<PropertyGroup>
    <TargetFramework>net6.0-windows10.0.17763</TargetFramework>
</PropertyGroup>

Once you've set your TFM, you can now use WinRT API's such as TaskbarManager.

An example:

using Windows.Foundation.Metadata;
using Windows.UI.Shell;

if (ApiInformation.IsTypePresent("Windows.UI.Shell.TaskbarManager"))
{
    var taskbarManager = TaskbarManager.GetDefault();
    bool isPinningAllowed = taskbarManager.IsPinningAllowed;
    bool isPinned = await TaskbarManager.GetDefault().IsCurrentAppPinnedAsync();
    if (isPinningAllowed && !isPinned)
    {
        // if pinning is allowed, and our app is not pinned, request to be pinned
        await taskbarManager.RequestPinCurrentAppAsync();
    }
}

When you call RequestPinCurrentAppAsync, the user will be presented with a dialog asking for permission to pin your app to the taskbar.

screenshot

Upvotes: 3

Related Questions