Programatically Pin\UnPin the folder from quick access menu in windows 10

前端 未结 1 2056
悲哀的现实
悲哀的现实 2021-02-15 14:09

I have a desktop application written in c#, and this application enables users to create the folder on their machine Hard drive . on windows 7 and 8, The App creates a shortcut

1条回答
  •  有刺的猬
    2021-02-15 14:48

    I know it's a bit late, but I've found a way to do it and thought maybe someone could still use this.

    So as was mentioned by Bradley Uffner, there is no API for this to avoid the constant abuse of such APIs. But there is still a (rather ugly) way to do it!

    I'm no expert in PowerShell, but I found a way to do it using PowerShell:

    # To add 'C:\path\to\folder' to quick access:
    $qa = New-Object -ComObject shell.application
    $qa.NameSpace('C:\path\to\folder').Self.InvokeVerb("pintohome")
    
    # To remove 'C:\path\to\folder' from quick access:
    ($qa.Namespace("shell:::{679F85CB-0220-4080-B29B-5540CC05AAB6}").Items() | Where-Object { $_.Path -EQ 'C:\path\to\folder' }).InvokeVerb("unpinfromhome")
    

    Which finally led me to the solution using C#:

    using System.Management.Automation;
    using System.Management.Automation.Runspaces
    
    private static void AddFolderToQuickAccess(string pathToFolder)
    {
        using (var runspace = RunspaceFactory.CreateRunspace())
        {
            runspace.Open();
            var ps = PowerShell.Create();
            var shellApplication =
                ps.AddCommand("New-Object").AddParameter("ComObject", "shell.application").Invoke();
            dynamic nameSpace = shellApplication.FirstOrDefault()?.Methods["NameSpace"].Invoke(pathToFolder);
            nameSpace?.Self.InvokeVerb("pintohome");
        }
    }
    
    private static void RemoveFolderFromQuickAccess(string pathToFolder)
    {
        using (var runspace = RunspaceFactory.CreateRunspace())
        {
            runspace.Open();
            var ps = PowerShell.Create();
            var removeScript =
                $"((New-Object -ComObject shell.application).Namespace(\"shell:::{{679f85cb-0220-4080-b29b-5540cc05aab6}}\").Items() | Where-Object {{ $_.Path -EQ \"{pathToFolder}\" }}).InvokeVerb(\"unpinfromhome\")";
    
            ps.AddScript(removeScript);
            ps.Invoke();
        }
    }
    

    NOTE: For this to work, you need to add a reference to System.Management.Automation which can easily be obtained as a nuget.

    0 讨论(0)
提交回复
热议问题