Tạo lối tắt trên Máy tính để bàn


106

Tôi muốn tạo lối tắt trỏ đến một số tệp EXE, trên máy tính để bàn, sử dụng .NET Framework 3.5 và dựa trên API Windows chính thức. Làm thế nào tôi có thể làm điều đó?


1
Sử dụng Mô hình Đối tượng Máy chủ Windows Script từ Rustam Irzaev là mô hình đáng tin cậy duy nhất cho một phím tắt thích hợp. ayush: Kỹ thuật này bỏ sót một loạt các tính năng như phím nóng và mô tả. Thorarin: ShellLink hoạt động tốt trong hầu hết các trường hợp, nhưng đáng chú ý là nó không hoạt động trong Windows XP và tạo ra các phím tắt không hợp lệ. Simon Mourier: Điều này rất hứa hẹn, nhưng tạo ra các phím tắt không hợp lệ trong Windows 8.
BrutalDev

Câu trả lời từ Simon Mourier là câu trả lời tốt nhất ở đây. Cách chính xác và chống đạn duy nhất để tạo phím tắt là sử dụng cùng một API mà hệ điều hành sử dụng và đây là giao diện IShellLink. Không sử dụng Windows Script Host hoặc tạo liên kết Web! Simon Mourier chỉ cách thực hiện điều này với 6 dòng mã. Bất kỳ ai gặp sự cố với phương pháp này SURELY đã vượt qua các đường dẫn không hợp lệ. Tôi đã thử nghiệm mã của anh ấy trên Windows XP, 7 và 10. Biên dịch ứng dụng của bạn thành "Bất kỳ CPU nào" để tránh sự cố với Windows 32/64 bit sử dụng các thư mục khác nhau cho Program Files, v.v.
Elmue

Câu trả lời:


120

Với các tùy chọn bổ sung như phím nóng, mô tả, v.v.

Lúc đầu, Project > Add Reference > COM > Windows Script Host Object Model.

using IWshRuntimeLibrary;

private void CreateShortcut()
{
  object shDesktop = (object)"Desktop";
  WshShell shell = new WshShell();
  string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\Notepad.lnk";
  IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
  shortcut.Description = "New shortcut for a Notepad";
  shortcut.Hotkey = "Ctrl+Shift+N";
  shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\notepad.exe";
  shortcut.Save();
}

2
Điều này thực sự gần gũi với tôi. Tôi cần thêm thư mục .exe vào thuộc tính "WorkingDirectory" trên phím tắt. (shortcut.WorkingDirectory) +1
samuelesque

4
Để chỉ định một chỉ mục biểu tượng (trong IconLocation), hãy sử dụng một giá trị như "path_to_icon_file, #", trong đó # là chỉ mục biểu tượng. Xem msdn.microsoft.com/en-us/library/xsy6k3ys(v=vs.84).aspx
Chris

1
cho đối số: shortcut.Arguments = "Seta Map mp_crash"; stackoverflow.com/a/18491229/2155778
Zolfaghari,

7
Môi trường.SpecialFolders.System - không tồn tại ... Môi trường.SpecialFolder.System - hoạt động.
JSWulf

chắc chắn bạn cũng cần thêm Microsoft.CSharp làm tài liệu tham khảo.
l1nuxuser

76

Lối tắt URL

private void urlShortcutToDesktop(string linkName, string linkUrl)
{
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

    using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    {
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=" + linkUrl);
    }
}

Phím tắt ứng dụng

private void appShortcutToDesktop(string linkName)
{
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

    using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    {
        string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=file:///" + app);
        writer.WriteLine("IconIndex=0");
        string icon = app.Replace('\\', '/');
        writer.WriteLine("IconFile=" + icon);
    }
}

Cũng kiểm tra ví dụ này .

Nếu bạn muốn sử dụng một số chức năng cụ thể của API thì bạn sẽ muốn sử dụng IShellLink interfacecả IPersistFile interface(thông qua COM interop).

Đây là một bài viết đi vào chi tiết những gì bạn cần làm, cũng như mã mẫu.


Những điều trên đang hoạt động tốt. Nhưng tôi muốn tạo lối tắt thông qua một số hàm API như DllImport ("coredll.dll")] public static extern int SHCreateShortcut (StringBuilder szShortcut, StringBuilder szTarget);
Vipin Arora

@Vipin tại sao? Có lý do gì tại sao bất kỳ giải pháp trên là không đủ tốt?
alex

8
soi mói: bạn có thể loại bỏ các dòng flush () như chấm dứt các Sử dụng khối của nên chăm sóc nó cho bạn
Newtopian

3
Tôi đã gặp rất nhiều vấn đề với phương pháp này ... Windows có xu hướng lưu định nghĩa phím tắt vào bộ nhớ cache ở đâu đó ... tạo một phím tắt như thế này, xóa nó, sau đó tạo một phím tắt có cùng tên nhưng khác URL ... rất có thể là windows sẽ mở URL cũ đã bị xóa khi bạn nhấp vào phím tắt. Câu trả lời Rustam của bên dưới (sử dụng .lnk thay vì .url) giải quyết vấn đề này đối với tôi
TCC

1
Câu trả lời tuyệt vời. Tốt hơn nhiều so với hệ thống ống nước COM kinh khủng mà bạn phải đối phó khi sử dụng tệp .lnk.
James Ko

61

Đây là đoạn mã không phụ thuộc vào đối tượng COM bên ngoài (WSH) và hỗ trợ các chương trình 32 bit và 64 bit:

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

namespace TestShortcut
{
    class Program
    {
        static void Main(string[] args)
        {
            IShellLink link = (IShellLink)new ShellLink();

            // setup shortcut information
            link.SetDescription("My Description");
            link.SetPath(@"c:\MyPath\MyProgram.exe");

            // save it
            IPersistFile file = (IPersistFile)link;
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            file.Save(Path.Combine(desktopPath, "MyLink.lnk"), false);
        }
    }

    [ComImport]
    [Guid("00021401-0000-0000-C000-000000000046")]
    internal class ShellLink
    {
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("000214F9-0000-0000-C000-000000000046")]
    internal interface IShellLink
    {
        void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out IntPtr pfd, int fFlags);
        void GetIDList(out IntPtr ppidl);
        void SetIDList(IntPtr pidl);
        void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
        void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
        void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
        void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
        void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
        void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
        void GetHotkey(out short pwHotkey);
        void SetHotkey(short wHotkey);
        void GetShowCmd(out int piShowCmd);
        void SetShowCmd(int iShowCmd);
        void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
        void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
        void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
        void Resolve(IntPtr hwnd, int fFlags);
        void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
    }
}

@BrutalDev - Điều gì không hoạt động? Tôi đã thử nghiệm nó trên Windows 8 x64 và nó hoạt động.
Simon Mourier

Cũng đang chạy Win8 x64, đã sao chép chính xác mẫu mã ở trên, nó tạo ra một biểu tượng trên màn hình của tôi không có đường dẫn. Việc thực thi liên kết chỉ mở trình thám hiểm đến màn hình. Đây là sự cố tương tự mà tôi gặp phải với ShellLink.cs nhưng trong Windows XP / 2003. Ví dụ duy nhất mà dứt khoát làm việc trên tất cả các phiên bản Windows là Rustam Irzaev bằng cách sử dụng WSHOM như tôi đã đề cập trong nhận xét của tôi cho câu hỏi chính: "Điều này đã được rất hứa hẹn, nhưng tạo ra các phím tắt không hợp lệ trong Windows 8"
BrutalDev

Tôi nhận được điều này để hoạt động trên Windows 8.1 x64, nhưng mã như được cung cấp ở đây ngay bây giờ không có định nghĩa cho IPersistFile. Tôi đã phải sao chép nó từ bài đăng ShellLink.cs để nó hoạt động.
Walter Wilfinger

Tôi không thấy bất kỳ lý do hữu hình nào khiến việc này không hoạt động. Dù sao, IPersistFile đã có sẵn trong System.Runtime.InteropServices.ComTypes
Simon Mourier

1
Giải pháp này không đặt đúng biểu tượng khi sử dụng SetIconLocationtrên Windows 10 64-bit với tệp thực thi 32-bit. Giải pháp được mô tả ở đây: stackoverflow.com/a/39282861 và tôi cũng nghi ngờ rằng đó là vấn đề tương tự với Windows 8 mà tất cả các máy khác đang gặp phải. Nó có thể liên quan đến các tệp exe 32-bit trên Windows 64-bit.
Maris B.

26

Bạn có thể sử dụng lớp ShellLink.cs này để tạo lối tắt.

Để lấy thư mục trên màn hình, hãy sử dụng:

var dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

hoặc sử dụng Environment.SpecialFolder.CommonDesktopDirectoryđể tạo nó cho tất cả người dùng.


6
@Vipin: nếu một giải pháp phù hợp với bạn, thông thường bạn nên tán thành nó. Ngoài ra, bạn nên chọn giải pháp tốt nhất và chấp nhận nó như câu trả lời cho vấn đề của bạn.
Thorarin

Điều này sẽ ghi đè exe hiện có bằng tệp lnk. Đã thử nghiệm trên Win10.
zwcloud

@zwcloud Mã này không ghi đè lên bất kỳ thứ gì vì nó không làm gì cả. Nó chỉ cho bạn biết các lớp và phương pháp sử dụng để làm việc với các phím tắt. Nếu mã của bạn đang ghi đè exe có trên bạn. Tôi sẽ xem xét cách bạn thực sự tạo tệp lnk để xem tại sao nó phá hủy exe của bạn.
Cdaragorn

15

Không cần tham khảo thêm:

using System;
using System.Runtime.InteropServices;

public class Shortcut
{

private static Type m_type = Type.GetTypeFromProgID("WScript.Shell");
private static object m_shell = Activator.CreateInstance(m_type);

[ComImport, TypeLibType((short)0x1040), Guid("F935DC23-1CF0-11D0-ADB9-00C04FD58A0B")]
private interface IWshShortcut
{
    [DispId(0)]
    string FullName { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0)] get; }
    [DispId(0x3e8)]
    string Arguments { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3e8)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3e8)] set; }
    [DispId(0x3e9)]
    string Description { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3e9)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3e9)] set; }
    [DispId(0x3ea)]
    string Hotkey { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ea)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ea)] set; }
    [DispId(0x3eb)]
    string IconLocation { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3eb)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3eb)] set; }
    [DispId(0x3ec)]
    string RelativePath { [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ec)] set; }
    [DispId(0x3ed)]
    string TargetPath { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ed)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ed)] set; }
    [DispId(0x3ee)]
    int WindowStyle { [DispId(0x3ee)] get; [param: In] [DispId(0x3ee)] set; }
    [DispId(0x3ef)]
    string WorkingDirectory { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ef)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ef)] set; }
    [TypeLibFunc((short)0x40), DispId(0x7d0)]
    void Load([In, MarshalAs(UnmanagedType.BStr)] string PathLink);
    [DispId(0x7d1)]
    void Save();
}

public static void Create(string fileName, string targetPath, string arguments, string workingDirectory, string description, string hotkey, string iconPath)
{
    IWshShortcut shortcut = (IWshShortcut)m_type.InvokeMember("CreateShortcut", System.Reflection.BindingFlags.InvokeMethod, null, m_shell, new object[] { fileName });
    shortcut.Description = description;
    shortcut.Hotkey = hotkey;
    shortcut.TargetPath = targetPath;
    shortcut.WorkingDirectory = workingDirectory;
    shortcut.Arguments = arguments;
    if (!string.IsNullOrEmpty(iconPath))
        shortcut.IconLocation = iconPath;
    shortcut.Save();
}
}

Để tạo lối tắt trên màn hình:

    string lnkFileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Notepad.lnk");
    Shortcut.Create(lnkFileName,
        System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "notepad.exe"),
        null, null, "Open Notepad", "Ctrl+Shift+N", null);

11

Tôi chỉ sử dụng cho ứng dụng của mình:

using IWshRuntimeLibrary; // > Ref > COM > Windows Script Host Object  
...   
private static void CreateShortcut()
    {
        string link = Environment.GetFolderPath( Environment.SpecialFolder.Desktop ) 
            + Path.DirectorySeparatorChar + Application.ProductName + ".lnk";
        var shell = new WshShell();
        var shortcut = shell.CreateShortcut( link ) as IWshShortcut;
        shortcut.TargetPath = Application.ExecutablePath;
        shortcut.WorkingDirectory = Application.StartupPath;
        //shortcut...
        shortcut.Save();
    }

Hoạt động hiệu quả, chỉ cần sao chép-dán nó
rluks 14/09/2016

9

Sử dụng ShellLink.cs tại vbAccelerator để tạo phím tắt của bạn một cách dễ dàng!

private static void AddShortCut()
{
using (ShellLink shortcut = new ShellLink())
{
    shortcut.Target = Application.ExecutablePath;
    shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
    shortcut.Description = "My Shorcut";
    shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
    shortcut.Save(SHORTCUT_FILEPATH);
}
}

3
Liên kết đó hiện đã chết, nhưng bạn có thể tìm thấy phiên bản lưu trữ của nó tại đây .
pswg

7

Đây là mã của tôi:

public static class ShortcutHelper
{
    #region Constants
    /// <summary>
    /// Default shortcut extension
    /// </summary>
    public const string DEFAULT_SHORTCUT_EXTENSION = ".lnk";

    private const string WSCRIPT_SHELL_NAME = "WScript.Shell";
    #endregion

    /// <summary>
    /// Create shortcut in current path.
    /// </summary>
    /// <param name="linkFileName">shortcut name(include .lnk extension.)</param>
    /// <param name="targetPath">target path</param>
    /// <param name="workingDirectory">working path</param>
    /// <param name="arguments">arguments</param>
    /// <param name="hotkey">hot key(ex: Ctrl+Shift+Alt+A)</param>
    /// <param name="shortcutWindowStyle">window style</param>
    /// <param name="description">shortcut description</param>
    /// <param name="iconNumber">icon index(start of 0)</param>
    /// <returns>shortcut file path.</returns>
    /// <exception cref="System.IO.FileNotFoundException"></exception>
    public static string CreateShortcut(
        string linkFileName,
        string targetPath,
        string workingDirectory = "",
        string arguments = "",
        string hotkey = "",
        ShortcutWindowStyles shortcutWindowStyle = ShortcutWindowStyles.WshNormalFocus,
        string description = "",
        int iconNumber = 0)
    {
        if (linkFileName.Contains(DEFAULT_SHORTCUT_EXTENSION) == false)
        {
            linkFileName = string.Format("{0}{1}", linkFileName, DEFAULT_SHORTCUT_EXTENSION);
        }

        if (File.Exists(targetPath) == false)
        {
            throw new FileNotFoundException(targetPath);
        }

        if (workingDirectory == string.Empty)
        {
            workingDirectory = Path.GetDirectoryName(targetPath);
        }

        string iconLocation = string.Format("{0},{1}", targetPath, iconNumber);

        if (Environment.Version.Major >= 4)
        {
            Type shellType = Type.GetTypeFromProgID(WSCRIPT_SHELL_NAME);
            dynamic shell = Activator.CreateInstance(shellType);
            dynamic shortcut = shell.CreateShortcut(linkFileName);

            shortcut.TargetPath = targetPath;
            shortcut.WorkingDirectory = workingDirectory;
            shortcut.Arguments = arguments;
            shortcut.Hotkey = hotkey;
            shortcut.WindowStyle = shortcutWindowStyle;
            shortcut.Description = description;
            shortcut.IconLocation = iconLocation;

            shortcut.Save();
        }
        else
        {
            Type shellType = Type.GetTypeFromProgID(WSCRIPT_SHELL_NAME);
            object shell = Activator.CreateInstance(shellType);
            object shortcut = shellType.InvokeMethod("CreateShortcut", shell, linkFileName);
            Type shortcutType = shortcut.GetType();

            shortcutType.InvokeSetMember("TargetPath", shortcut, targetPath);
            shortcutType.InvokeSetMember("WorkingDirectory", shortcut, workingDirectory);
            shortcutType.InvokeSetMember("Arguments", shortcut, arguments);
            shortcutType.InvokeSetMember("Hotkey", shortcut, hotkey);
            shortcutType.InvokeSetMember("WindowStyle", shortcut, shortcutWindowStyle);
            shortcutType.InvokeSetMember("Description", shortcut, description);
            shortcutType.InvokeSetMember("IconLocation", shortcut, iconLocation);

            shortcutType.InvokeMethod("Save", shortcut);
        }

        return Path.Combine(System.Windows.Forms.Application.StartupPath, linkFileName);
    }

    private static object InvokeSetMember(this Type type, string methodName, object targetInstance, params object[] arguments)
    {
        return type.InvokeMember(
            methodName,
            BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
            null,
            targetInstance,
            arguments);
    }

    private static object InvokeMethod(this Type type, string methodName, object targetInstance, params object[] arguments)
    {
        return type.InvokeMember(
            methodName,
            BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
            null,
            targetInstance,
            arguments);
    }

    /// <summary>
    /// windows styles
    /// </summary>
    public enum ShortcutWindowStyles
    {
        /// <summary>
        /// Hide
        /// </summary>
        WshHide = 0,
        /// <summary>
        /// NormalFocus
        /// </summary>
        WshNormalFocus = 1,
        /// <summary>
        /// MinimizedFocus
        /// </summary>
        WshMinimizedFocus = 2,
        /// <summary>
        /// MaximizedFocus
        /// </summary>
        WshMaximizedFocus = 3,
        /// <summary>
        /// NormalNoFocus
        /// </summary>
        WshNormalNoFocus = 4,
        /// <summary>
        /// MinimizedNoFocus
        /// </summary>
        WshMinimizedNoFocus = 6,
    }
}

5

CHỈNH SỬA: Tôi không khuyên bạn nên giải pháp này nữa. Nếu vẫn không có phương pháp nào tốt hơn là sử dụng công cụ tạo tập lệnh Windows, ít nhất hãy sử dụng giải pháp của @ Mehmet để gọi công cụ trực tiếp thay vì tạo một tập lệnh văn bản thuần túy trong bộ nhớ.

Chúng tôi đã sử dụng VBScript để tạo một phím tắt. Nó không cần p / Invoke, COM Interop và các DLL bổ sung. Nó hoạt động như thế này:

  • Tạo VBScript trong thời gian chạy với các tham số được chỉ định của phương thức CreateShortcut C #
  • Lưu VBScript này trong một tệp tạm thời
  • Chờ tập lệnh hoàn thành
  • Xóa tệp tạm thời

Của bạn đây:

static string _scriptTempFilename;

/// <summary>
/// Creates a shortcut at the specified path with the given target and
/// arguments.
/// </summary>
/// <param name="path">The path where the shortcut will be created. This should
///     be a file with the LNK extension.</param>
/// <param name="target">The target of the shortcut, e.g. the program or file
///     or folder which will be opened.</param>
/// <param name="arguments">The additional command line arguments passed to the
///     target.</param>
public static void CreateShortcut(string path, string target, string arguments)
{
    // Check if link path ends with LNK or URL
    string extension = Path.GetExtension(path).ToUpper();
    if (extension != ".LNK" && extension != ".URL")
    {
        throw new ArgumentException("The path of the shortcut must have the extension .lnk or .url.");
    }

    // Get temporary file name with correct extension
    _scriptTempFilename = Path.GetTempFileName();
    File.Move(_scriptTempFilename, _scriptTempFilename += ".vbs");

    // Generate script and write it in the temporary file
    File.WriteAllText(_scriptTempFilename, String.Format(@"Dim WSHShell
Set WSHShell = WScript.CreateObject({0}WScript.Shell{0})
Dim Shortcut
Set Shortcut = WSHShell.CreateShortcut({0}{1}{0})
Shortcut.TargetPath = {0}{2}{0}
Shortcut.WorkingDirectory = {0}{3}{0}
Shortcut.Arguments = {0}{4}{0}
Shortcut.Save",
        "\"", path, target, Path.GetDirectoryName(target), arguments),
        Encoding.Unicode);

    // Run the script and delete it after it has finished
    Process process = new Process();
    process.StartInfo.FileName = _scriptTempFilename;
    process.Start();
    process.WaitForExit();
    File.Delete(_scriptTempFilename);
}

3

Đây là một Phương pháp mở rộng (Đã thử nghiệm), với các nhận xét để giúp bạn.

using IWshRuntimeLibrary;
using System;

namespace Extensions
{
    public static class XShortCut
    {
        /// <summary>
        /// Creates a shortcut in the startup folder from a exe as found in the current directory.
        /// </summary>
        /// <param name="exeName">The exe name e.g. test.exe as found in the current directory</param>
        /// <param name="startIn">The shortcut's "Start In" folder</param>
        /// <param name="description">The shortcut's description</param>
        /// <returns>The folder path where created</returns>
        public static string CreateShortCutInStartUpFolder(string exeName, string startIn, string description)
        {
            var startupFolderPath = Environment.SpecialFolder.Startup.GetFolderPath();
            var linkPath = startupFolderPath + @"\" + exeName + "-Shortcut.lnk";
            var targetPath = Environment.CurrentDirectory + @"\" + exeName;
            XFile.Delete(linkPath);
            Create(linkPath, targetPath, startIn, description);
            return startupFolderPath;
        }

        /// <summary>
        /// Create a shortcut
        /// </summary>
        /// <param name="fullPathToLink">the full path to the shortcut to be created</param>
        /// <param name="fullPathToTargetExe">the full path to the exe to 'really execute'</param>
        /// <param name="startIn">Start in this folder</param>
        /// <param name="description">Description for the link</param>
        public static void Create(string fullPathToLink, string fullPathToTargetExe, string startIn, string description)
        {
            var shell = new WshShell();
            var link = (IWshShortcut)shell.CreateShortcut(fullPathToLink);
            link.IconLocation = fullPathToTargetExe;
            link.TargetPath = fullPathToTargetExe;
            link.Description = description;
            link.WorkingDirectory = startIn;
            link.Save();
        }
    }
}

Và một ví dụ sử dụng:

XShortCut.CreateShortCutInStartUpFolder(THEEXENAME, 
    Environment.CurrentDirectory,
    "Starts some executable in the current directory of application");

Parm thứ nhất đặt tên exe (tìm thấy trong thư mục hiện tại) Parm thứ hai là thư mục "Start In" và parm thứ 3 là mô tả phím tắt.

Ví dụ về việc sử dụng mã này

Quy ước đặt tên của liên kết không để lại sự mơ hồ về những gì nó sẽ làm. Để kiểm tra liên kết chỉ cần nhấp đúp vào nó.

Lưu ý cuối cùng: bản thân ứng dụng (đích) phải có hình ảnh ICON được liên kết với nó. Liên kết có thể dễ dàng xác định vị trí ICON trong exe. Nếu ứng dụng đích có nhiều hơn một biểu tượng, bạn có thể mở thuộc tính của liên kết và thay đổi biểu tượng thành bất kỳ biểu tượng nào khác được tìm thấy trong exe.


Tôi nhận được thông báo lỗi rằng .GetFolderPath () không tồn tại. Tương tự đối với XFile.Delete. Tôi đang thiếu gì?
RalphF

Có lỗi xảy ra ở đây không? Môi trường.SpecialFolder.Startup.GetFolderPath ();
John Peters

2

Tôi sử dụng tham chiếu "Windows Script Host Object Model" để tạo lối tắt.

Thêm "Mô hình đối tượng máy chủ Windows Script" vào tham chiếu dự án

và để tạo lối tắt trên vị trí cụ thể:

    void CreateShortcut(string linkPath, string filename)
    {
        // Create shortcut dir if not exists
        if (!Directory.Exists(linkPath))
            Directory.CreateDirectory(linkPath);

        // shortcut file name
        string linkName = Path.ChangeExtension(Path.GetFileName(filename), ".lnk");

        // COM object instance/props
        IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
        IWshRuntimeLibrary.IWshShortcut sc = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(linkName);
        sc.Description = "some desc";
        //shortcut.IconLocation = @"C:\..."; 
        sc.TargetPath = linkPath;
        // save shortcut to target
        sc.Save();
    }

0
private void CreateShortcut(string executablePath, string name)
    {
        CMDexec("echo Set oWS = WScript.CreateObject('WScript.Shell') > CreateShortcut.vbs");
        CMDexec("echo sLinkFile = '" + Environment.GetEnvironmentVariable("homedrive") + "\\users\\" + Environment.GetEnvironmentVariable("username") + "\\desktop\\" + name + ".ink' >> CreateShortcut.vbs");
        CMDexec("echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs");
        CMDexec("echo oLink.TargetPath = '" + executablePath + "' >> CreateShortcut.vbs");
        CMDexec("echo oLink.Save >> CreateShortcut.vbs");
        CMDexec("cscript CreateShortcut.vbs");
        CMDexec("del CreateShortcut.vbs");
    }

0

Tôi đã tạo một lớp trình bao bọc dựa trên câu trả lời của Rustam Irzaev bằng cách sử dụng IWshRuntimeLibrary.

IWshRuntimeLibrary -> References -> COM> Windows Script Host Object Model

using System;
using System.IO;
using IWshRuntimeLibrary;
using File = System.IO.File;

public static class Shortcut
{
    public static void CreateShortcut(string originalFilePathAndName, string destinationSavePath)
    {
        string fileName = Path.GetFileNameWithoutExtension(originalFilePathAndName);
        string originalFilePath = Path.GetDirectoryName(originalFilePathAndName);

        string link = destinationSavePath + Path.DirectorySeparatorChar + fileName + ".lnk";
        var shell = new WshShell();
        var shortcut = shell.CreateShortcut(link) as IWshShortcut;
        if (shortcut != null)
        {
            shortcut.TargetPath = originalFilePathAndName;
            shortcut.WorkingDirectory = originalFilePath;
            shortcut.Save();
        }
    }

    public static void CreateStartupShortcut()
    {
        CreateShortcut(System.Reflection.Assembly.GetEntryAssembly()?.Location, Environment.GetFolderPath(Environment.SpecialFolder.Startup));
    }

    public static void DeleteShortcut(string originalFilePathAndName, string destinationSavePath)
    {
        string fileName = Path.GetFileNameWithoutExtension(originalFilePathAndName);
        string originalFilePath = Path.GetDirectoryName(originalFilePathAndName);

        string link = destinationSavePath + Path.DirectorySeparatorChar + fileName + ".lnk";
        if (File.Exists(link)) File.Delete(link);
    }

    public static void DeleteStartupShortcut()
    {
        DeleteShortcut(System.Reflection.Assembly.GetEntryAssembly()?.Location, Environment.GetFolderPath(Environment.SpecialFolder.Startup));
    }
}

-2

Đối với Windows Vista / 7/8/10, bạn có thể tạo một liên kết biểu tượng thông qua mklink.

Process.Start("cmd.exe", $"/c mklink {linkName} {applicationPath}");

Ngoài ra, hãy gọi CreateSymbolicLinkqua P / Invoke.


Điều này không liên quan gì đến một phím tắt.
Matt,
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.