c# 纯代码方式创建快捷方式

原文:c# 纯代码方式创建快捷方式

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

namespace ShortcutNamespace
{
    class MyShortcut
    {
        [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="shortcutPath">快捷方式路径。</param>
        /// <param name="targetPath">目标路径。</param>
        /// <param name="parameter"></param>
        /// <param name="workingDirectory">工作路径。</param>
        /// <param name="description">快捷键描述。</param>

        public static bool CreateShortcut(string shortcutPath, string targetPath, string parameter, 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.SetArguments(parameter);
                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 = MyShortcut.GetDeskDir();
            }
            return MyShortcut.CreateShortcut(MyShortcut.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 = MyShortcut.GetProgramsDir();
            }
            string shortcutPath = MyShortcut.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 MyShortcut.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 = MyShortcut.GetProgramsDir();
            }
            string shortcutPath = MyShortcut.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 MyShortcut.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);
        }
    }
}

  

时间: 2024-08-28 03:11:40

c# 纯代码方式创建快捷方式的相关文章

《iOS 9 开发指南》——第6章,第6.9节实战演练——纯代码实现UI设计

6.9 实战演练--纯代码实现UI设计iOS 9 开发指南在本节的内容中,将通过具体实例讲解另外一种实现UI界面设计的方法:纯代码方式.在本实例中,将不使用Xcode 7的故事板设计工具,而是用编写代码的方式实现界面布局. 实例6-2 将Xcode界面连接到代码(1)使用Xcode 7创建一个iOS 9程序,在自动生成的工程文件中删除故事板文件.如图6-33所示. (2)开始编写代码,文件AppDelegate.h的具体实现代码如下所示: #import <UIKit/UIKit.h> @in

c#通过纯代码创建桌面快捷方式、创建程序菜单项、将网页添加到收藏夹

c#通过纯代码创建桌面快捷方式.创建程序菜单项.将网页添加到收藏夹 本文章源代码Src下载地址:http://download.csdn.net/detail/testcs_dn/5141580 开始菜单>程序菜单项: 添加到收藏夹: 相关函数代码: public const int SW_SHOWNORMAL = 1; /// <summary> /// 创建快捷方式. /// </summary> /// <param name="shortcutPath

C# 无需COM组件创建快捷方式的实现代码_C#教程

看了一下手中的一些小工具, 很多都是单文件但可以创建快捷方式, 于是翻遍 Google, 最后终于在俄罗斯论坛 RSDN 找到了一个很强大的类. 类文件下载: http://asen.googlecode.com/files/Shortcut.cs (无注释精简版)RSDN 原帖: http://www.rsdn.ru/forum/src/3098615.flat.aspx (带英文注释) 使用方法很简单, 把这个文件添加到你的项目中, 然后用法跟 COM 组件那个类似, 但稍有不同: 复制代码

js 创建快捷方式的代码(fso)_javascript技巧

复制代码 代码如下: <script type="text/javascript" language="javascript"> // 创建快捷方式[浏览器设置要低,ff不支持] function createShortcut() { var fso = new ActiveXObject("Scripting.FileSystemObject"); var shell = new ActiveXObject("WScrip

iOS界面布局之三——纯代码的autoLayout及布局动画

iOS界面布局之三--纯代码的autoLayout及布局动画 一.引言         关于界面布局,apple的策略已经趋于成熟,autolayout的优势在开发中也已经展现的淋漓尽致.除了使用storyBoard进行布局约束的拖拽,有时我们也需要在代码中进行autolayout的布局设置,Masonry库可以方便的创建约束属性,实际上,我们也没有必要再使用系统原生的代码来创建和设置约束,这篇博客只作为使用的方法备忘.前几篇布局介绍的链接如下: 使用autoresizing进行界面布局:htt

史上比较用心的纯代码实现AutoLayout

入职有两三个月了吧,都是使用 Objective-C 纯代码(虽然有时候偷偷参杂一些 Swift 开源库)来编写公司APP,写布局的时候几乎都是要么在初始化的时候用 initWithFrame,要么就初始化完毕之后用 view.frame.虽然这种方法很直观,一眼就可以看出这个 view 的位置以及大小,但是坏处也是有的,比如说在计算的时候麻烦等等. 概述 使用 Objective-C 纯代码编写 AutoLayout,看 AutoLayout 的字面理解就是自动布局,听起来好像蛮屌的样子.说白

ios开发UI篇—使用纯代码自定义UItableviewcell实现一个简单的微博界面布局

一.实现效果 二.使用纯代码自定义一个tableview的步骤 1.新建一个继承自UITableViewCell的类 2.重写initWithStyle:reuseIdentifier:方法 添加所有需要显示的子控件(不需要设置子控件的数据和frame, 子控件要添加到contentView中) 进行子控件一次性的属性设置(有些属性只需要设置一次, 比如字体\固定的图片) 3.提供2个模型 数据模型: 存放文字数据\图片数据 frame模型: 存放数据模型\所有子控件的frame\cell的高度

看实例学VFP:编程方式创建类

上两个例子中介绍了使用"类设计器"来交互方式创建类,与交互方式相对应的,也可以用编程方式创建类.不过用这种方式来创建类很麻烦,并且需要极大的耐心去调试,相对来说用得比较少. 算是扩充一下知识面吧,本文对编程方式定义类的语句格式做一个简单的介绍,但是不必深究和浪费太多的时间,毕竟已经有可视化的.强大的"类设计器"可以用了:否则VFP这三个字母中,打头的这个V(Visual)也就失去其意义了.本文末尾给出了编程方式创建类的一个简单示例代码,运行时界面如下图: 运行时单击

在bottle框架中以类的方式创建应用

在bottle框架中,使用route修饰符将请求路由到与之对应的响应方法.这种特性非常适合路由请求与 方法,但却给在bottle中使用类来创建应用带了麻烦. class SanYou: app = Bottle() @app.route('/') def homepage(self): return "Welcome!" app1 = SanYou().app app2 = SanYou.app 以上代码中无论是app1还是app2,均返回TypeError: homepage() t