comparison ShortcutKeyFinder/Win32Helpers.cs @ 0:209d9210c18f default tip

It works.
author Brad Greco <brad@bgreco.net>
date Sat, 25 Jun 2016 13:42:54 +1000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:209d9210c18f
1 using System;
2 using System.Drawing;
3 using System.Runtime.InteropServices;
4 using System.Runtime.InteropServices.ComTypes;
5 using System.Text;
6
7 namespace ShortcutKeyFinder
8 {
9 /// <summary>Various functions to call the Win32 API</summary>
10 /// <remarks>Method signatures taken from http://www.pinvoke.net/ </remarks>
11 class Win32Helpers
12 {
13 public const int STGM_READ = 0x00000000;
14 public const int STGM_READWRITE = 0x00000002;
15 public const int ILD_NORMAL = 0;
16 public const int SW_SHOWNORMAL = 1;
17 public const uint SEE_MASK_INVOKEIDLIST = 0x0000000C;
18 public const uint BCM_SETSHIELD = 0x160C;
19 public const int SHGFI_SMALLICON = 0x000000001;
20 public const int SHGFI_ICON = 0x000000100;
21 public const int SHGFI_DISPLAYNAME = 0x000000200;
22 public const int SHGFI_SYSICONINDEX = 0x000004000;
23
24
25 #region GetShortcutHotkey, SetShortcutHotkey
26
27 // The CharSet must match the CharSet of the corresponding PInvoke signature
28 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
29 struct WIN32_FIND_DATAW
30 {
31 public uint dwFileAttributes;
32 public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
33 public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
34 public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
35 public uint nFileSizeHigh;
36 public uint nFileSizeLow;
37 public uint dwReserved0;
38 public uint dwReserved1;
39 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
40 public string cFileName;
41 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
42 public string cAlternateFileName;
43 }
44
45 /// <summary>IShellLink.GetPath fFlags: Flags that specify the type of path information to retrieve</summary>
46 [Flags()]
47 enum SLGP_FLAGS
48 {
49 /// <summary>Retrieves the standard short (8.3 format) file name</summary>
50 SLGP_SHORTPATH = 0x1,
51 /// <summary>Retrieves the Universal Naming Convention (UNC) path name of the file</summary>
52 SLGP_UNCPRIORITY = 0x2,
53 /// <summary>Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded</summary>
54 SLGP_RAWPATH = 0x4
55 }
56
57 /// <summary>IShellLink.Resolve fFlags</summary>
58 [Flags()]
59 enum SLR_FLAGS
60 {
61 /// <summary>
62 /// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
63 /// the high-order word of fFlags can be set to a time-out value that specifies the
64 /// maximum amount of time to be spent resolving the link. The function returns if the
65 /// link cannot be resolved within the time-out duration. If the high-order word is set
66 /// to zero, the time-out duration will be set to the default value of 3,000 milliseconds
67 /// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
68 /// duration, in milliseconds.
69 /// </summary>
70 SLR_NO_UI = 0x1,
71 /// <summary>Obsolete and no longer used</summary>
72 SLR_ANY_MATCH = 0x2,
73 /// <summary>If the link object has changed, update its path and list of identifiers.
74 /// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine
75 /// whether or not the link object has changed.</summary>
76 SLR_UPDATE = 0x4,
77 /// <summary>Do not update the link information</summary>
78 SLR_NOUPDATE = 0x8,
79 /// <summary>Do not execute the search heuristics</summary>
80 SLR_NOSEARCH = 0x10,
81 /// <summary>Do not use distributed link tracking</summary>
82 SLR_NOTRACK = 0x20,
83 /// <summary>Disable distributed link tracking. By default, distributed link tracking tracks
84 /// removable media across multiple devices based on the volume name. It also uses the
85 /// Universal Naming Convention (UNC) path to track remote file systems whose drive letter
86 /// has changed. Setting SLR_NOLINKINFO disables both types of tracking.</summary>
87 SLR_NOLINKINFO = 0x40,
88 /// <summary>Call the Microsoft Windows Installer</summary>
89 SLR_INVOKE_MSI = 0x80
90 }
91
92 /// <summary>The IShellLink interface allows Shell links to be created, modified, and resolved</summary>
93 [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]
94 interface IShellLinkW
95 {
96 /// <summary>Retrieves the path and file name of a Shell link object</summary>
97 void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags);
98 /// <summary>Retrieves the list of item identifiers for a Shell link object</summary>
99 void GetIDList(out IntPtr ppidl);
100 /// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary>
101 void SetIDList(IntPtr pidl);
102 /// <summary>Retrieves the description string for a Shell link object</summary>
103 void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
104 /// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary>
105 void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
106 /// <summary>Retrieves the name of the working directory for a Shell link object</summary>
107 void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
108 /// <summary>Sets the name of the working directory for a Shell link object</summary>
109 void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
110 /// <summary>Retrieves the command-line arguments associated with a Shell link object</summary>
111 void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
112 /// <summary>Sets the command-line arguments for a Shell link object</summary>
113 void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
114 /// <summary>Retrieves the hot key for a Shell link object</summary>
115 void GetHotkey(out ushort pwHotkey);
116 /// <summary>Sets a hot key for a Shell link object</summary>
117 void SetHotkey(ushort wHotkey);
118 /// <summary>Retrieves the show command for a Shell link object</summary>
119 void GetShowCmd(out int piShowCmd);
120 /// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary>
121 void SetShowCmd(int iShowCmd);
122 /// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary>
123 void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath,
124 int cchIconPath, out int piIcon);
125 /// <summary>Sets the location (path and index) of the icon for a Shell link object</summary>
126 void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
127 /// <summary>Sets the relative path to the Shell link object</summary>
128 void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
129 /// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary>
130 void Resolve(IntPtr hwnd, SLR_FLAGS fFlags);
131 /// <summary>Sets the path and file name of a Shell link object</summary>
132 void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
133 }
134
135 /// <summary>Retrieves the hotkey assigned to a shortcut (.lnk) file</summary>
136 /// <param name="path">Path to a shortcut (.lnk) file</param>
137 /// <returns>A binary value representing the shortcut's hotkey</returns>
138 public static ushort GetShortcutHotkey(string path)
139 {
140 Type obj = Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"), true);
141 IShellLinkW link = Activator.CreateInstance(obj) as IShellLinkW;
142
143 ((IPersistFile)link).Load(path, STGM_READ);
144 ushort hotkey;
145 link.GetHotkey(out hotkey);
146 return hotkey;
147 }
148
149 /// <summary>Assigns a hotkey to a shortcut (.lnk) file</summary>
150 /// <param name="path">Path to an exising shortcut (.lnk) file to modify</param>
151 /// <param name="hotkey">Binary value containing the hotkey to set</param>
152 public static bool SetShortcutHotkey(string path, ushort hotkey)
153 {
154 Type obj = Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"), true);
155 IShellLinkW link = Activator.CreateInstance(obj) as IShellLinkW;
156
157 try
158 {
159 ((IPersistFile)link).Load(path, STGM_READWRITE);
160 link.SetHotkey(hotkey);
161 ((IPersistFile)link).Save(path, false);
162 return true;
163 }
164 catch
165 {
166 return false;
167 }
168 }
169
170 #endregion
171
172 #region GetFileInfo
173
174 [DllImport("shell32.dll", CharSet = CharSet.Auto)]
175 public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);
176
177 [DllImport("comctl32.dll", SetLastError = true)]
178 public static extern IntPtr ImageList_GetIcon(IntPtr himl, int i, int flags);
179
180 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
181 public struct SHFILEINFO
182 {
183 public IntPtr hIcon;
184 public int iIcon;
185 public uint dwAttributes;
186 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
187 public string szDisplayName;
188 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
189 public string szTypeName;
190 };
191
192 /// <summary>Retrieves the hotkey assigned to a shortcut (.lnk) file</summary>
193 /// <param name="path">Path of the file to retreive properties from</param>
194 /// <param name="smallIcon">Set to true to retreive the 16x16 icon. By default, the 32x32 icon is retrieved.</param>
195 /// <param name="noOverlays">Set to true to remove icon overlays as displayed in Windows Explorer (for example, the shortcut arrow)</param>
196 public static FileInfo GetFileInfo(string path, bool smallIcon = false, bool noOverlays = false)
197 {
198 SHFILEINFO info = new SHFILEINFO();
199 uint flags = SHGFI_DISPLAYNAME;
200 if (smallIcon)
201 flags |= SHGFI_SMALLICON;
202 if (noOverlays)
203 flags |= SHGFI_SYSICONINDEX;
204 else
205 flags |= SHGFI_ICON;
206 IntPtr shgfi = SHGetFileInfo(path, 0, ref info, (uint)Marshal.SizeOf(info), flags);
207
208 if (shgfi == IntPtr.Zero)
209 return null;
210
211 if (noOverlays)
212 {
213 IntPtr icon = ImageList_GetIcon(shgfi, info.iIcon, ILD_NORMAL);
214 return new FileInfo(info.szDisplayName, icon != IntPtr.Zero ? Icon.FromHandle(icon) : null);
215 }
216 else
217 return new FileInfo(info.szDisplayName, Icon.FromHandle(info.hIcon));
218 }
219
220 #endregion
221
222 #region ShowFilePropertiesWindow
223
224 [DllImport("shell32.dll", CharSet = CharSet.Auto)]
225 static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
226
227 [StructLayout(LayoutKind.Sequential)]
228 public struct SHELLEXECUTEINFO
229 {
230 public int cbSize;
231 public uint fMask;
232 public IntPtr hwnd;
233 [MarshalAs(UnmanagedType.LPTStr)]
234 public string lpVerb;
235 [MarshalAs(UnmanagedType.LPTStr)]
236 public string lpFile;
237 [MarshalAs(UnmanagedType.LPTStr)]
238 public string lpParameters;
239 [MarshalAs(UnmanagedType.LPTStr)]
240 public string lpDirectory;
241 public int nShow;
242 public IntPtr hInstApp;
243 public IntPtr lpIDList;
244 [MarshalAs(UnmanagedType.LPTStr)]
245 public string lpClass;
246 public IntPtr hkeyClass;
247 public uint dwHotKey;
248 public IntPtr hIcon;
249 public IntPtr hProcess;
250 }
251
252 /// <summary>Displays the Properties window of a file</summary>
253 /// <param name="path">File to display the properties window for</param>
254 /// <param name="parentWindow">Handle to the parent window for error messages to be displayed</param>
255 public static void ShowFilePropertiesWindow(string path, IntPtr parentWindow = default(IntPtr))
256 {
257 SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
258 info.cbSize = Marshal.SizeOf(info);
259 info.fMask = SEE_MASK_INVOKEIDLIST;
260 info.hwnd = parentWindow;
261 info.lpVerb = "properties";
262 info.lpFile = path;
263 info.nShow = SW_SHOWNORMAL;
264 ShellExecuteEx(ref info);
265 }
266
267 #endregion
268
269 #region AddUacShield
270
271 [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
272 static extern int SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, IntPtr lParam);
273
274 /// <summary>Adds a UAC shield icon to a button</summary>
275 /// <param name="button">Button to add the shield icon to</param>
276 public static void AddUacShield(System.Windows.Forms.Button button)
277 {
278 button.FlatStyle = System.Windows.Forms.FlatStyle.System;
279 SendMessage(button.Handle, BCM_SETSHIELD, 0, (IntPtr)1);
280 }
281
282 #endregion
283 }
284
285 /// <summary>Class to hold basic file information</summary>
286 class FileInfo
287 {
288 public string DisplayName;
289 public Icon Icon;
290
291 public FileInfo(string DisplayName, Icon Icon)
292 {
293 this.DisplayName = DisplayName;
294 this.Icon = Icon;
295 }
296 }
297 }