view 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
line wrap: on
line source

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;

namespace ShortcutKeyFinder
{
    /// <summary>Various functions to call the Win32 API</summary>
    /// <remarks>Method signatures taken from http://www.pinvoke.net/ </remarks>
    class Win32Helpers
    {
        public const int STGM_READ = 0x00000000;
        public const int STGM_READWRITE = 0x00000002;
        public const int ILD_NORMAL = 0;
        public const int SW_SHOWNORMAL = 1;
        public const uint SEE_MASK_INVOKEIDLIST = 0x0000000C;
        public const uint BCM_SETSHIELD = 0x160C;
        public const int SHGFI_SMALLICON = 0x000000001;
        public const int SHGFI_ICON         = 0x000000100;
        public const int SHGFI_DISPLAYNAME  = 0x000000200;
        public const int SHGFI_SYSICONINDEX = 0x000004000;


        #region GetShortcutHotkey, SetShortcutHotkey

        // The CharSet must match the CharSet of the corresponding PInvoke signature
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct WIN32_FIND_DATAW
        {
            public uint dwFileAttributes;
            public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
            public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
            public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
            public uint nFileSizeHigh;
            public uint nFileSizeLow;
            public uint dwReserved0;
            public uint dwReserved1;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string cFileName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
            public string cAlternateFileName;
        }

        /// <summary>IShellLink.GetPath fFlags: Flags that specify the type of path information to retrieve</summary>
        [Flags()]
        enum SLGP_FLAGS
        {
            /// <summary>Retrieves the standard short (8.3 format) file name</summary>
            SLGP_SHORTPATH = 0x1,
            /// <summary>Retrieves the Universal Naming Convention (UNC) path name of the file</summary>
            SLGP_UNCPRIORITY = 0x2,
            /// <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>
            SLGP_RAWPATH = 0x4
        }

        /// <summary>IShellLink.Resolve fFlags</summary>
        [Flags()]
        enum SLR_FLAGS
        {
            /// <summary>
            /// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
            /// the high-order word of fFlags can be set to a time-out value that specifies the
            /// maximum amount of time to be spent resolving the link. The function returns if the
            /// link cannot be resolved within the time-out duration. If the high-order word is set
            /// to zero, the time-out duration will be set to the default value of 3,000 milliseconds
            /// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
            /// duration, in milliseconds.
            /// </summary>
            SLR_NO_UI = 0x1,
            /// <summary>Obsolete and no longer used</summary>
            SLR_ANY_MATCH = 0x2,
            /// <summary>If the link object has changed, update its path and list of identifiers.
            /// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine
            /// whether or not the link object has changed.</summary>
            SLR_UPDATE = 0x4,
            /// <summary>Do not update the link information</summary>
            SLR_NOUPDATE = 0x8,
            /// <summary>Do not execute the search heuristics</summary>
            SLR_NOSEARCH = 0x10,
            /// <summary>Do not use distributed link tracking</summary>
            SLR_NOTRACK = 0x20,
            /// <summary>Disable distributed link tracking. By default, distributed link tracking tracks
            /// removable media across multiple devices based on the volume name. It also uses the
            /// Universal Naming Convention (UNC) path to track remote file systems whose drive letter
            /// has changed. Setting SLR_NOLINKINFO disables both types of tracking.</summary>
            SLR_NOLINKINFO = 0x40,
            /// <summary>Call the Microsoft Windows Installer</summary>
            SLR_INVOKE_MSI = 0x80
        }

        /// <summary>The IShellLink interface allows Shell links to be created, modified, and resolved</summary>
        [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]
        interface IShellLinkW
        {
            /// <summary>Retrieves the path and file name of a Shell link object</summary>
            void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags);
            /// <summary>Retrieves the list of item identifiers for a Shell link object</summary>
            void GetIDList(out IntPtr ppidl);
            /// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary>
            void SetIDList(IntPtr pidl);
            /// <summary>Retrieves the description string for a Shell link object</summary>
            void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
            /// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary>
            void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
            /// <summary>Retrieves the name of the working directory for a Shell link object</summary>
            void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
            /// <summary>Sets the name of the working directory for a Shell link object</summary>
            void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
            /// <summary>Retrieves the command-line arguments associated with a Shell link object</summary>
            void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
            /// <summary>Sets the command-line arguments for a Shell link object</summary>
            void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
            /// <summary>Retrieves the hot key for a Shell link object</summary>
            void GetHotkey(out ushort pwHotkey);
            /// <summary>Sets a hot key for a Shell link object</summary>
            void SetHotkey(ushort wHotkey);
            /// <summary>Retrieves the show command for a Shell link object</summary>
            void GetShowCmd(out int piShowCmd);
            /// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary>
            void SetShowCmd(int iShowCmd);
            /// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary>
            void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath,
                int cchIconPath, out int piIcon);
            /// <summary>Sets the location (path and index) of the icon for a Shell link object</summary>
            void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
            /// <summary>Sets the relative path to the Shell link object</summary>
            void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
            /// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary>
            void Resolve(IntPtr hwnd, SLR_FLAGS fFlags);
            /// <summary>Sets the path and file name of a Shell link object</summary>
            void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
        }

        /// <summary>Retrieves the hotkey assigned to a shortcut (.lnk) file</summary>
        /// <param name="path">Path to a shortcut (.lnk) file</param>
        /// <returns>A binary value representing the shortcut's hotkey</returns>
        public static ushort GetShortcutHotkey(string path)
        {
            Type obj = Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"), true);
            IShellLinkW link = Activator.CreateInstance(obj) as IShellLinkW;

            ((IPersistFile)link).Load(path, STGM_READ);
            ushort hotkey;
            link.GetHotkey(out hotkey);
            return hotkey;
        }

        /// <summary>Assigns a hotkey to a shortcut (.lnk) file</summary>
        /// <param name="path">Path to an exising shortcut (.lnk) file to modify</param>
        /// <param name="hotkey">Binary value containing the hotkey to set</param>
        public static bool SetShortcutHotkey(string path, ushort hotkey)
        {
            Type obj = Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"), true);
            IShellLinkW link = Activator.CreateInstance(obj) as IShellLinkW;

            try
            {
                ((IPersistFile)link).Load(path, STGM_READWRITE);
                link.SetHotkey(hotkey);
                ((IPersistFile)link).Save(path, false);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region GetFileInfo

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);

        [DllImport("comctl32.dll", SetLastError = true)]
        public static extern IntPtr ImageList_GetIcon(IntPtr himl, int i, int flags);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        /// <summary>Retrieves the hotkey assigned to a shortcut (.lnk) file</summary>
        /// <param name="path">Path of the file to retreive properties from</param>
        /// <param name="smallIcon">Set to true to retreive the 16x16 icon. By default, the 32x32 icon is retrieved.</param>
        /// <param name="noOverlays">Set to true to remove icon overlays as displayed in Windows Explorer (for example, the shortcut arrow)</param>
        public static FileInfo GetFileInfo(string path, bool smallIcon = false, bool noOverlays = false)
        {
            SHFILEINFO info = new SHFILEINFO();
            uint flags = SHGFI_DISPLAYNAME;
            if (smallIcon)
                flags |= SHGFI_SMALLICON;
            if (noOverlays)
                flags |= SHGFI_SYSICONINDEX;
            else
                flags |= SHGFI_ICON;
            IntPtr shgfi = SHGetFileInfo(path, 0, ref info, (uint)Marshal.SizeOf(info), flags);

            if (shgfi == IntPtr.Zero)
                return null;

            if (noOverlays)
            {
                IntPtr icon = ImageList_GetIcon(shgfi, info.iIcon, ILD_NORMAL);
                return new FileInfo(info.szDisplayName, icon != IntPtr.Zero ? Icon.FromHandle(icon) : null);
            }
            else
                return new FileInfo(info.szDisplayName, Icon.FromHandle(info.hIcon));
        }

        #endregion

        #region ShowFilePropertiesWindow

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);

        [StructLayout(LayoutKind.Sequential)]
        public struct SHELLEXECUTEINFO
        {
            public int cbSize;
            public uint fMask;
            public IntPtr hwnd;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string lpVerb;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string lpFile;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string lpParameters;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string lpDirectory;
            public int nShow;
            public IntPtr hInstApp;
            public IntPtr lpIDList;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string lpClass;
            public IntPtr hkeyClass;
            public uint dwHotKey;
            public IntPtr hIcon;
            public IntPtr hProcess;
        }

        /// <summary>Displays the Properties window of a file</summary>
        /// <param name="path">File to display the properties window for</param>
        /// <param name="parentWindow">Handle to the parent window for error messages to be displayed</param>
        public static void ShowFilePropertiesWindow(string path, IntPtr parentWindow = default(IntPtr))
        {
            SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
            info.cbSize = Marshal.SizeOf(info);
            info.fMask = SEE_MASK_INVOKEIDLIST;
            info.hwnd = parentWindow;
            info.lpVerb = "properties";
            info.lpFile = path;
            info.nShow = SW_SHOWNORMAL;
            ShellExecuteEx(ref info);
        }

        #endregion

        #region AddUacShield

        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, IntPtr lParam);

        /// <summary>Adds a UAC shield icon to a button</summary>
        /// <param name="button">Button to add the shield icon to</param>
        public static void AddUacShield(System.Windows.Forms.Button button)
        {
            button.FlatStyle = System.Windows.Forms.FlatStyle.System;
            SendMessage(button.Handle, BCM_SETSHIELD, 0, (IntPtr)1);
        }

        #endregion
    }

    /// <summary>Class to hold basic file information</summary>
    class FileInfo
    {
        public string DisplayName;
        public Icon Icon;

        public FileInfo(string DisplayName, Icon Icon)
        {
            this.DisplayName = DisplayName;
            this.Icon = Icon;
        }
    }
}