After learning how to pin to the Taskbar programmatically in part 1, the next step is to pin a program on the network. One easy solution commonly given is to pin another program such as calculator, or a local copy of the network program, and change the created shortcut to point to the program on the network. But this involves typing and clicking and is error-prone, which means inevitably some users will be unable to do it. We are software developers. We are supposed to be creating solutions to users’ problems, and we don’t want to bother them with these annoyances. So unless you plan on doing this manually for each one of your users, read on..
Pinning programs with a Jump List
There is another major drawback to the methods linked above. If your application uses a Jump list, it will not be displayed on the pinned button, it will appear on a new button and be gone when the program is closed, rendering the Jump list practically useless. What you get is something similar to this, and the underlying cause in some cases is actually the same.
The reason for this is that when you pin a program through explorer, the shortcut includes the AppID used in the Jump list. When you pin it using the method above, the shortcut doesn’t include the AppID, and the Jump list isn’t associated with it.
Putting it all together
So what we have to do, like in the solutions above, is to pin a local program such as notepad.exe, and change the properties of the shortcut that is created, including the appID, to the correct values, all programmatically. After that we notify the shell to update itself, so we can see the new icon.
I changed the program from the last post based on this article from emoacht, which is modified from another article based on another one which is ultimately a wrapper around the IShellLink interface.
You can download the source here, or a compiled version here.
The new program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace PintoTB10 { class Program { static readonly string help = "Syntax: PintoTB10 [/pin | /unpin | /pinnetwork /sn {shortcut name} /a[rgs] {args} /id {appID} /si {start in}] {program}"; static int Main(string[] args) { if (args.Length > 0 && args[0].ToLower() == "/pinnetwork") { var result = PinNetwork(args.Skip(1)); if (result == 2) Console.WriteLine(help); return result; } if (args.Length < 1) { Console.WriteLine(help); return 1; } bool pin = true; string fileName = args[0]; if (args.Length >= 2) { if (args[0].ToLower() == "/pin") pin = true; else if (args[0].ToLower() == "/unpin") pin = false; else { Console.WriteLine(help); return 1; } fileName = args[1]; } if (!File.Exists(fileName)) { Console.WriteLine("File " + fileName + " not found"); return 1; } bool success = true; try { Utils.ChangeImagePathName("explorer.exe"); success = Utils.PinUnpinTaskbar(fileName, pin); } finally { Utils.RestoreImagePathName(); } Console.WriteLine(success ? "OK" : "Failed"); return success ? 0 : 1; } enum LinkProperties { None, ShortcutName, Arguments, AppUserModelID, StartIn, KnownName }; static Dictionary<string, LinkProperties> PropertiesDictionary = new Dictionary<string, LinkProperties> { {"SN", LinkProperties.ShortcutName}, {"A", LinkProperties.Arguments}, {"ARGS", LinkProperties.Arguments}, {"ID", LinkProperties.AppUserModelID}, {"SI", LinkProperties.StartIn}, {"KN", LinkProperties.KnownName}, }; private static int PinNetwork(IEnumerable<string> args) { try { var last = LinkProperties.None; string ShortcutName = null; string TargetPath = null; string Arguments = null; string AppUserModelID = null; string StartIn = null; string KnownName = null; foreach (var arg in args) { if (last == LinkProperties.None) { if (arg[0] == '/') { var key = arg.Substring(1).ToUpper(); if (!PropertiesDictionary.TryGetValue(key, out last)) return 2; } else { TargetPath = arg; } } else { if (last == LinkProperties.ShortcutName) ShortcutName = arg; else if (last == LinkProperties.Arguments) Arguments = arg; else if (last == LinkProperties.AppUserModelID) AppUserModelID = arg; else if (last == LinkProperties.StartIn) StartIn = arg; else if (last == LinkProperties.KnownName) KnownName = arg; last = LinkProperties.None; } } if (String.IsNullOrWhiteSpace(ShortcutName) || String.IsNullOrWhiteSpace(TargetPath)) return 2; string shortcutPath, tempFilePath = null; if (KnownName != null) shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar", KnownName + ".lnk"); else { shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar", "notepad.lnk"); var windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows); tempFilePath = Path.Combine(windir, "system32", "notepad.exe"); } var finalShortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar", ShortcutName + ".lnk"); if (File.Exists(finalShortcutPath)) return 1; if (!File.Exists(shortcutPath)) { if (KnownName != null) { var tempPath = Path.GetTempPath(); var fileName = Path.GetFileName(TargetPath); tempFilePath = Path.Combine(tempPath, fileName); File.Copy(TargetPath, tempFilePath); } bool ok; try { Utils.ChangeImagePathName("explorer.exe"); ok = Utils.PinUnpinTaskbar(tempFilePath, true); } finally { Utils.RestoreImagePathName(); if (KnownName != null) File.Delete(tempFilePath); } if (!ok || !File.Exists(shortcutPath)) return 1; } using (ShellLink shortcut = new ShellLink()) { shortcut.TargetPath = TargetPath; shortcut.Arguments = Arguments; shortcut.AppUserModelID = AppUserModelID; shortcut.StartIn = StartIn; shortcut.IconLocation = TargetPath + ", 0"; shortcut.Save(shortcutPath); } System.Threading.Thread.Sleep(800); File.Move(shortcutPath, finalShortcutPath); System.Threading.Thread.Sleep(800); SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero); return 0; } catch (Exception ex) { Console.WriteLine(ex.Message); return 1; } } [DllImport("Shell32.dll")] internal static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2); } } |
Here is the ShellLink wrapper which I took from emoacht and just added a few properties:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 |
using System; using System.IO; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; using ComTypes = System.Runtime.InteropServices.ComTypes; namespace PintoTB10 { // Based on https://emoacht.wordpress.com/2012/11/14/csharp-appusermodelid/ // Modified from http://smdn.jp/programming/tips/createlnk/ // Originally from http://www.vbaccelerator.com/home/NET/Code/Libraries/Shell_Projects/Creating_and_Modifying_Shortcuts/article.asp // Partly based on Sending toast notifications from desktop apps sample public class ShellLink : IDisposable { #region Win32 and COM // IShellLink Interface [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")] private interface IShellLinkW { uint GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, ref WIN32_FIND_DATAW pfd, uint fFlags); uint GetIDList(out IntPtr ppidl); uint SetIDList(IntPtr pidl); uint GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName); uint SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName); uint GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath); uint SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir); uint GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); uint SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs); uint GetHotKey(out ushort pwHotkey); uint SetHotKey(ushort wHotKey); uint GetShowCmd(out int piShowCmd); uint SetShowCmd(int iShowCmd); uint GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon); uint SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); uint SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, uint dwReserved); uint Resolve(IntPtr hwnd, uint fFlags); uint SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile); } // ShellLink CoClass (ShellLink object) [ComImport, ClassInterface(ClassInterfaceType.None), Guid("00021401-0000-0000-C000-000000000046")] private class CShellLink { } // WIN32_FIND_DATAW Structure [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Unicode)] private struct WIN32_FIND_DATAW { public uint dwFileAttributes; public ComTypes.FILETIME ftCreationTime; public ComTypes.FILETIME ftLastAccessTime; public ComTypes.FILETIME ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } // IPropertyStore Interface [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99")] private interface IPropertyStore { uint GetCount([Out] out uint cProps); uint GetAt([In] uint iProp, out PropertyKey pkey); uint GetValue([In] ref PropertyKey key, [Out] PropVariant pv); uint SetValue([In] ref PropertyKey key, [In] PropVariant pv); uint Commit(); } // PropertyKey Structure // Narrowed down from PropertyKey.cs of Windows API Code Pack 1.1 [StructLayout(LayoutKind.Sequential, Pack = 4)] private struct PropertyKey { #region Fields private Guid formatId; // Unique GUID for property private Int32 propertyId; // Property identifier (PID) #endregion #region Public Properties public Guid FormatId { get { return formatId; } } public Int32 PropertyId { get { return propertyId; } } #endregion #region Constructor public PropertyKey(Guid formatId, Int32 propertyId) { this.formatId = formatId; this.propertyId = propertyId; } public PropertyKey(string formatId, Int32 propertyId) { this.formatId = new Guid(formatId); this.propertyId = propertyId; } #endregion } // PropVariant Class (only for string value) // Narrowed down from PropVariant.cs of Windows API Code Pack 1.1 // Originally from http://blogs.msdn.com/b/adamroot/archive/2008/04/11 // /interop-with-propvariants-in-net.aspx [StructLayout(LayoutKind.Explicit)] private sealed class PropVariant : IDisposable { #region Fields [FieldOffset(0)] ushort valueType; // Value type // [FieldOffset(2)] // ushort wReserved1; // Reserved field // [FieldOffset(4)] // ushort wReserved2; // Reserved field // [FieldOffset(6)] // ushort wReserved3; // Reserved field [FieldOffset(8)] IntPtr ptr; // Value #endregion #region Public Properties // Value type (System.Runtime.InteropServices.VarEnum) public VarEnum VarType { get { return (VarEnum)valueType; } set { valueType = (ushort)value; } } // Whether value is empty or null public bool IsNullOrEmpty { get { return (valueType == (ushort)VarEnum.VT_EMPTY || valueType == (ushort)VarEnum.VT_NULL); } } // Value (only for string value) public string Value { get { return Marshal.PtrToStringUni(ptr); } } #endregion #region Constructor public PropVariant() { } // Construct with string value public PropVariant(string value) { if (value == null) throw new ArgumentException("Failed to set value."); valueType = (ushort)VarEnum.VT_LPWSTR; ptr = Marshal.StringToCoTaskMemUni(value); } #endregion #region Destructor ~PropVariant() { Dispose(); } public void Dispose() { PropVariantClear(this); GC.SuppressFinalize(this); } #endregion } [DllImport("Ole32.dll", PreserveSig = false)] private extern static void PropVariantClear([In, Out] PropVariant pvar); #endregion #region Fields private IShellLinkW shellLinkW = null; // Name = System.AppUserModel.ID // ShellPKey = PKEY_AppUserModel_ID // FormatID = 9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3 // PropID = 5 // Type = String (VT_LPWSTR) private readonly PropertyKey AppUserModelIDKey = new PropertyKey("{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}", 5); private const int MAX_PATH = 260; private const int INFOTIPSIZE = 1024; private const int STGM_READ = 0x00000000; // STGM constants private const uint SLGP_UNCPRIORITY = 0x0002; // SLGP flags #endregion #region Private Properties (Interfaces) private IPersistFile PersistFile { get { IPersistFile PersistFile = shellLinkW as IPersistFile; if (PersistFile == null) throw new COMException("Failed to create IPersistFile."); else return PersistFile; } } private IPropertyStore PropertyStore { get { IPropertyStore PropertyStore = shellLinkW as IPropertyStore; if (PropertyStore == null) throw new COMException("Failed to create IPropertyStore."); else return PropertyStore; } } #endregion #region Public Properties (Minimal) // Path of loaded shortcut file public string ShortcutFile { get { string shortcutFile; PersistFile.GetCurFile(out shortcutFile); return shortcutFile; } } // Path of target file public string TargetPath { get { // No limitation to length of buffer string in the case of Unicode though. StringBuilder targetPath = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); VerifySucceeded(shellLinkW.GetPath(targetPath, targetPath.Capacity, ref data, SLGP_UNCPRIORITY)); return targetPath.ToString(); } set { VerifySucceeded(shellLinkW.SetPath(value)); } } // Path to start the target in public string StartIn { get { // No limitation to length of buffer string in the case of Unicode though. StringBuilder targetPath = new StringBuilder(MAX_PATH); VerifySucceeded(shellLinkW.GetWorkingDirectory(targetPath, targetPath.Capacity)); return targetPath.ToString(); } set { VerifySucceeded(shellLinkW.SetWorkingDirectory(value)); } } public string Arguments { get { // No limitation to length of buffer string in the case of Unicode though. StringBuilder arguments = new StringBuilder(INFOTIPSIZE); VerifySucceeded(shellLinkW.GetArguments(arguments, arguments.Capacity)); return arguments.ToString(); } set { VerifySucceeded(shellLinkW.SetArguments(value)); } } // AppUserModelID to be used for Windows 7 or later. public string AppUserModelID { get { using (PropVariant pv = new PropVariant()) { VerifySucceeded(PropertyStore.GetValue(AppUserModelIDKey, pv)); if (pv.Value == null) return "Null"; else return pv.Value; } } set { using (PropVariant pv = new PropVariant(value)) { VerifySucceeded(PropertyStore.SetValue(AppUserModelIDKey, pv)); VerifySucceeded(PropertyStore.Commit()); } } } public string IconLocation { get { // No limitation to length of buffer string in the case of Unicode though. StringBuilder pszIconPath = new StringBuilder(INFOTIPSIZE); int piIcon; VerifySucceeded(shellLinkW.GetIconLocation(pszIconPath, pszIconPath.Capacity, out piIcon)); return pszIconPath.ToString() + ", " + piIcon; } set { var parts = value.Split(','); var pszIconPath = parts[0]; int iIcon = 0; if (parts.Length > 1) int.TryParse(parts[1], out iIcon); VerifySucceeded(shellLinkW.SetIconLocation(pszIconPath, iIcon)); } } #endregion #region Constructor public ShellLink() : this(null) { } // Construct with loading shortcut file. public ShellLink(string file) { try { shellLinkW = (IShellLinkW)new CShellLink(); } catch { throw new COMException("Failed to create ShellLink object."); } if (file != null) Load(file); } #endregion #region Destructor ~ShellLink() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (shellLinkW != null) { // Release all references. Marshal.FinalReleaseComObject(shellLinkW); shellLinkW = null; } } #endregion #region Methods // Save shortcut file. public void Save() { string file = ShortcutFile; if (file == null) throw new InvalidOperationException("File name is not given."); else Save(file); } public void Save(string file) { if (file == null) throw new ArgumentNullException("File name is required."); else PersistFile.Save(file, true); } // Load shortcut file. public void Load(string file) { if (!File.Exists(file)) throw new FileNotFoundException("File is not found.", file); else PersistFile.Load(file, STGM_READ); } // Verify if operation succeeded. public static void VerifySucceeded(uint hresult) { if (hresult > 1) throw new InvalidOperationException("Failed with HRESULT: " + hresult.ToString("X")); } #endregion } } |
Hi,
can you please provide a example on how to use it with the /pinnetwork and Appid parameter
Thanks
Suppose your program is on the company network on Z:\companyapps\main.exe, it has a Jumplist and the appID is ‘main.prod’. You would run:
Pinto10TB /pinnetwork /sn Main /id main.prod /si Z:\companyapps Z:\companyapps\main.exe
.It will pin notepad.exe to the taskbar and then change all the properties of the shortcut to the ones you specify.
That’s assuming you wrote the program and know the appID. If you don’t, let me know and I’ll update the post explaining an easy way to find it out.
does not work for windows 10 pro x64
C:\PintoTB10\bin\Release>PintoTB10.exe /pin D:\Regshot\Regshot.exe
return Ok
but regshot is not in C:\Users\Eric\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu folder
Humm sorry, it’s taskbar, i want to start menu… my mistake…
Hi,
Have you worked out how to pin applications with a ‘protocol’ path or like the special shortcuts for Microsoft Office programs?
ie:
Target: softwarecenter:
Target: Microsoft Office Professional Plus 2016
or is that what you do with the AppID?
Brendan
Alex, Can you assist in figuring out Start Menu pinning in Windows 10 1903? My code, modified from yours has stopped working. I’ve got TaskBar pinning working again using PEB manipulation from here…
https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Masquerade-PEB.ps1
But it won’t touch the Start menu. Syspin has it working but it’s closed source…
http://www.technosys.net/products/utils/pintotaskbar
Can you get in touch if possible?
https://pinto10blog.wordpress.com/2016/09/10/pinto10/
Stuart
Hi Stuart! I’m a bit busy with other projects so I can’t promise, but if I have time I’ll look into it.