Windows 7 - Taskbar - Pin or Unpin Program Links

后端 未结 8 1452
不思量自难忘°
不思量自难忘° 2021-01-12 04:13

As in title, is there any Win32 API to do that?

8条回答
  •  北海茫月
    2021-01-12 04:41

    It works, but not for all OS, e.g. Windows 10:

        [DllImport("kernel32.dll")]
        private static extern IntPtr LoadLibrary(string dllName);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
    
        private static void PinUnpinTaskBar(string filePath, bool pin)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException(filePath + " not exists!");
    
            int MAX_PATH = 255;
            var actionIndex = pin ? 5386 : 5387; // 5386 is the DLL index for"Pin to Tas&kbar", ref. http://www.win7dll.info/shell32_dll.html
            StringBuilder szPinToStartLocalized = new StringBuilder(MAX_PATH);
            IntPtr hShell32 = LoadLibrary("Shell32.dll");
            LoadString(hShell32, (uint)actionIndex, szPinToStartLocalized, MAX_PATH);
            string localizedVerb = szPinToStartLocalized.ToString();
    
            // create the shell application object
            dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
    
            string path = Path.GetDirectoryName(filePath);
            string fileName = Path.GetFileName(filePath);
    
            dynamic directory = shellApplication.NameSpace(path);
            dynamic link = directory.ParseName(fileName);
    
            dynamic verbs = link.Verbs();
            for (int i = 0; i < verbs.Count(); i++)
            {
                dynamic verb = verbs.Item(i);
    
                if ((pin && verb.Name.Equals(localizedVerb)) || (!pin && verb.Name.Contains(localizedVerb)))
                {
                    verb.DoIt();
                    break;
                }
            }
        }
    

提交回复
热议问题