C#分享辅助类:快捷方式辅助(ShortcutHandler)

30 篇文章 1 订阅
该代码示例展示了如何在C#中利用COMInterop创建桌面快捷方式和程序菜单快捷方式。通过`ShortcutHandler`类,可以调用`CreateDesktopShortcut`和`CreateProgramsShortcut`方法,指定目标路径、描述、图标位置和工作目录来创建快捷方式。
摘要由CSDN通过智能技术生成

名称

方法

创建快捷方式

CreateShortcut

创建桌面快捷方式

CreateDesktopShortcut

创建程序菜单快捷方式

CreateProgramsShortcut

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace Wsfly
{
    /// <summary>
    /// 快捷方式
    /// </summary>
    public class ShortcutHandler
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct FILETIME
        {
            uint dwLowDateTime;
            uint dwHighDateTime;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct WIN32_FIND_DATA
        {
            public const int MAX_PATH = 260;

            uint dwFileAttributes;
            FILETIME ftCreationTime;
            FILETIME ftLastAccessTime;
            FILETIME ftLastWriteTime;
            uint nFileSizeHight;
            uint nFileSizeLow;
            uint dwOID;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
            string cFileName;
        }

        [ComImport]
        [Guid("0000010c-0000-0000-c000-000000000046")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IPersist
        {
            [PreserveSig]
            void GetClassID(out Guid pClassID);
        }

        [ComImport]
        [Guid("0000010b-0000-0000-C000-000000000046")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IPersistFile
            : IPersist
        {
            new void GetClassID(out Guid pClassID);

            [PreserveSig]
            int IsDirty();

            [PreserveSig]
            void Load(
                [MarshalAs(UnmanagedType.LPWStr)] string pszFileName,
                uint dwMode);

            [PreserveSig]
            void Save(
                [MarshalAs(UnmanagedType.LPWStr)] string pszFileName,
                [MarshalAs(UnmanagedType.Bool)] bool fRemember);

            [PreserveSig]
            void SaveCompleted([MarshalAs(UnmanagedType.LPWStr)] string pszFileName);

            [PreserveSig]
            void GetCurFile([MarshalAs(UnmanagedType.LPWStr)] string ppszFileName);
        }

        [ComImport]
        [Guid("000214F9-0000-0000-C000-000000000046")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IShellLink
        {
            [PreserveSig]
            void GetPath(
                [MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 1)] out string pszFile,
                int cch,
                ref WIN32_FIND_DATA pfd,
                uint fFlags);

            [PreserveSig]
            void GetIDList(out IntPtr ppidl);

            [PreserveSig]
            void SetIDList(IntPtr ppidl);

            [PreserveSig]
            void GetDescription(
                [MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 1)] out string pszName,
                int cch);

            [PreserveSig]
            void SetDescription(
                [MarshalAs(UnmanagedType.LPWStr)] string pszName);

            [PreserveSig]
            void GetWorkingDirectory(
                [MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 1)] out string pszDir,
                int cch);

            [PreserveSig]
            void SetWorkingDirectory(
                [MarshalAs(UnmanagedType.LPWStr)] string pszDir);

            [PreserveSig]
            void GetArguments(
                [MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 1)] out string pszArgs,
                int cch);

            [PreserveSig]
            void SetArguments(
                [MarshalAs(UnmanagedType.LPWStr)] string pszArgs);

            [PreserveSig]
            void GetHotkey(out ushort pwHotkey);

            [PreserveSig]
            void SetHotkey(ushort wHotkey);

            [PreserveSig]
            void GetShowCmd(out int piShowCmd);

            [PreserveSig]
            void SetShowCmd(int iShowCmd);

            [PreserveSig]
            void GetIconLocation(
                [MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 1)] out string pszIconPath,
                int cch,
                out int piIcon);

            [PreserveSig]
            void SetIconLocation(
                [MarshalAs(UnmanagedType.LPWStr)] string pszIconPath,
                int iIcon);

            [PreserveSig]
            void SetRelativePath(
                [MarshalAs(UnmanagedType.LPWStr)] string pszPathRel,
                uint dwReserved);

            [PreserveSig]
            void Resolve(
                IntPtr hwnd,
                uint fFlags);

            [PreserveSig]
            void SetPath(
                [MarshalAs(UnmanagedType.LPWStr)] string pszFile);
        }

        [GuidAttribute("00021401-0000-0000-C000-000000000046")]
        [ClassInterfaceAttribute(ClassInterfaceType.None)]
        [ComImportAttribute()]
        public class CShellLink
        {
        }

        public const int SW_SHOWNORMAL = 1;
        /// <summary>
        /// 创建快捷方式。
        /// </summary>
        /// <param name="shortcutPath">快捷方式路径。</param>
        /// <param name="targetPath">目标路径。</param>
        /// <param name="workingDirectory">工作路径。</param>
        /// <param name="description">快捷键描述。</param>
        public static bool CreateShortcut(string shortcutPath, string targetPath, string workingDirectory, string description, string iconLocation = null)
        {
            try
            {
                CShellLink cShellLink = new CShellLink();
                IShellLink iShellLink = (IShellLink)cShellLink;
                iShellLink.SetDescription(description);
                iShellLink.SetShowCmd(SW_SHOWNORMAL);
                iShellLink.SetPath(targetPath);
                iShellLink.SetWorkingDirectory(workingDirectory);

                if (!string.IsNullOrEmpty(iconLocation))
                {
                    iShellLink.SetIconLocation(iconLocation, 0);
                }
            
                IPersistFile iPersistFile = (IPersistFile)iShellLink;
                iPersistFile.Save(shortcutPath, false);
                Marshal.ReleaseComObject(iPersistFile);
                iPersistFile = null;
                Marshal.ReleaseComObject(iShellLink);
                iShellLink = null;
                Marshal.ReleaseComObject(cShellLink);
                cShellLink = null;
                return true;
            }
            catch //(System.Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 创建桌面快捷方式
        /// </summary>
        /// <param name="targetPath">可执行文件路径</param>
        /// <param name="description">快捷方式名称</param>
        /// <param name="iconLocation">快捷方式图标路径</param>
        /// <param name="workingDirectory">工作路径</param>
        /// <returns></returns>
        public static bool CreateDesktopShortcut(string targetPath, string description, string iconLocation = null, string workingDirectory = null)
        {
            if (string.IsNullOrEmpty(workingDirectory))
            {
                workingDirectory = ShortcutHandler.GetDeskDir();
            }
            return ShortcutHandler.CreateShortcut(ShortcutHandler.GetDeskDir() + "\\" + description + ".lnk", targetPath, workingDirectory, description, iconLocation);
        }

        /// <summary>
        /// 创建程序菜单快捷方式
        /// </summary>
        /// <param name="targetPath">可执行文件路径</param>
        /// <param name="description">快捷方式名称</param>
        /// <param name="menuName">程序菜单中子菜单名称,为空则不创建子菜单</param>
        /// <param name="iconLocation">快捷方式图标路径</param>
        /// <param name="workingDirectory">工作路径</param>
        /// <returns></returns>
        public static bool CreateProgramsShortcut(string targetPath, string description, string menuName, string iconLocation = null, string workingDirectory = null)
        {
            if (string.IsNullOrEmpty(workingDirectory))
            {
                workingDirectory = ShortcutHandler.GetProgramsDir();
            }
            string shortcutPath = ShortcutHandler.GetProgramsDir();
            if (!string.IsNullOrEmpty(menuName))
            {
                shortcutPath += "\\" + menuName;
                if (!System.IO.Directory.Exists(shortcutPath))
                {
                    try
                    {
                        System.IO.Directory.CreateDirectory(shortcutPath);
                    }
                    catch //(System.Exception ex)
                    {
                        return false;
                    }
                }
            }
            shortcutPath += "\\" + description + ".lnk";
            return ShortcutHandler.CreateShortcut(shortcutPath, targetPath, workingDirectory, description, iconLocation);
        }

        public static bool AddFavorites(string url, string description, string folderName, string iconLocation = null, string workingDirectory = null)
        {
            if (string.IsNullOrEmpty(workingDirectory))
            {
                workingDirectory = ShortcutHandler.GetProgramsDir();
            }
            string shortcutPath = ShortcutHandler.GetFavoriteDir();
            if (!string.IsNullOrEmpty(folderName))
            {
                shortcutPath += "\\" + folderName;
                if (!System.IO.Directory.Exists(shortcutPath))
                {
                    try
                    {
                        System.IO.Directory.CreateDirectory(shortcutPath);
                    }
                    catch //(System.Exception ex)
                    {
                        return false;
                    }
                }
            }
            shortcutPath += "\\" + description + ".lnk";
            return ShortcutHandler.CreateShortcut(shortcutPath, url, workingDirectory, description, iconLocation);
        }

        internal const uint SHGFP_TYPE_CURRENT = 0;
        internal const int MAX_PATH = 260;
        internal const uint CSIDL_COMMON_STARTMENU = 0x0016;              // All Users\Start Menu
        internal const uint CSIDL_COMMON_PROGRAMS = 0x0017;               // All Users\Start Menu\Programs
        internal const uint CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019;       // All Users\Desktop
        internal const uint CSIDL_PROGRAM_FILES = 0x0026;                 // C:\Program Files
        internal const uint CSIDL_FLAG_CREATE = 0x8000;                   // new for Win2K, or this in to force creation of folder
        internal const uint CSIDL_COMMON_FAVORITES = 0x001f;              // All Users Favorites

        [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
        internal static extern void SHGetFolderPathW(
            IntPtr hwndOwner,
            int nFolder,
            IntPtr hToken,
            uint dwFlags,
            IntPtr pszPath);

        internal static string SHGetFolderPath(int nFolder)
        {
            string pszPath = new string(' ', MAX_PATH);
            IntPtr bstr = Marshal.StringToBSTR(pszPath);
            SHGetFolderPathW(IntPtr.Zero, nFolder, IntPtr.Zero, SHGFP_TYPE_CURRENT, bstr);
            string path = Marshal.PtrToStringBSTR(bstr);
            int index = path.IndexOf('\0');
            string path2 = path.Substring(0, index);
            Marshal.FreeBSTR(bstr);
            return path2;
        }


        public static string GetSpecialFolderPath(uint csidl)
        {
            return SHGetFolderPath((int)(csidl | CSIDL_FLAG_CREATE));
        }

        public static string GetDeskDir()
        {
            return GetSpecialFolderPath(CSIDL_COMMON_DESKTOPDIRECTORY);
        }

        public static string GetProgramsDir()
        {
            return GetSpecialFolderPath(CSIDL_COMMON_PROGRAMS);
        }

        public static string GetFavoriteDir()
        {
            return GetSpecialFolderPath(CSIDL_COMMON_FAVORITES);
        }
    }
}
超级多的C#辅助大全 网上有各式各样的帮助,公共,但是比较零碎,经常有人再群里或者各种社交账号上问有没有这个helper,那个helper,于是萌生了收集全部helper的念头,以便日后使用。各式各样的几乎都能找到,所有功能性代码都是独立的之间没有联系,可以单独引用至项目。 1. C#读取AD域里用户名或组 2. Chart图形 3. cmd 4. Cookie&Session 5. CSV文件转换 6. DataTable转实体 7. DBHelper 8. DecimalUtility及中文大写数字 9. DLL 10. Excel操作 11. FTP操作 12. H5-微信 13. Html操作 14. INI文件读写 15. IP辅助 16. Javascript 17. Json 18. JSON操作 19. JS操作 20. Lib 21. Mime 22. Net 23. NPOI 24. obj 25. packages 26. Path 27. PDF 28. Properties 29. QueryString 地址栏参数 30. RDLC直接打印帮助 31. ResourceManager 32. RMB 33. SqlHelper 34. SQL语句拦截器 35. URL的操作 36. VerifyCode 37. XML操作 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. 条形码转HTML 67. 检测是否有Sql危险字符 68. 正则表达式 69. 汉字转拼音 70. 注册表操作 71. 科学计数,数学 72. 型转换 73. 系统操作相关的公共 74. 缓存 75. 网站安全 76. 网站路径操作 77. 网络 78. 视频帮助 79. 视频转换 80. 计划任务 81. 邮件 82. 邮件2 83. 配置文件操作 84. 阿里云 85. 随机数 86. 页面辅助 87. 验证码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MOZ-Soft

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值