데스크톱에 바로 가기 만들기


106

.NET Framework 3.5를 사용하고 공식 Windows API를 사용하여 데스크톱에서 일부 EXE 파일을 가리키는 바로 가기를 만들고 싶습니다. 어떻게 할 수 있습니까?


1
Rustam Irzaev의 Windows 스크립트 호스트 개체 모델을 사용하는 것은 적절한 바로 가기를위한 유일한 신뢰할 수있는 모델입니다. ayush :이 기술은 단축키 및 설명과 같은 많은 기능이 누락되었습니다. Thorarin : ShellLink는 대부분의 경우 잘 작동하지만 특히 Windows XP에서는 작동하지 않으며 잘못된 바로 가기를 만듭니다. Simon Mourier : 이것은 매우 유망했지만 Windows 8에서 잘못된 바로 가기를 만듭니다.
— BrutalDev

Simon Mourier의 대답이 여기에서 가장 좋은 대답입니다. 바로 가기를 만드는 유일한 정확하고 방탄 한 방법은 운영 체제에서 사용하는 것과 동일한 API를 사용하는 것입니다. 이것이 IShellLink 인터페이스입니다. Windows Script Host를 사용하거나 웹 링크를 만들지 마십시오! Simon Mourier가 6 줄의 코드로이를 수행하는 방법을 보여줍니다. 이 방법에 문제가있는 사람은 확실히 잘못된 경로를 전달했습니다. Windows XP, 7 및 10에서 그의 코드를 테스트했습니다. Program Files 등에 다른 폴더를 사용하는 32/64 비트 Windows의 문제를 방지하기 위해 앱을 "모든 CPU"로 컴파일합니다.
— Elmue

답변:


120

핫키, 설명 등과 같은 추가 옵션이 있습니다.

처음에는 프로젝트 > 참조 추가 > COM > Windows 스크립트 호스트 개체 모델입니다.

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
이것은 나에게 정말 가깝습니다. 바로 가기의 "WorkingDirectory"속성에 .exe의 디렉터리를 추가해야했습니다. (shortcut.WorkingDirectory) +1
— samuelesque 2014 년

4
아이콘 인덱스를 지정하려면 (IconLocation에서) "path_to_icon_file, #"과 같은 값을 사용하십시오. 여기서 #은 아이콘 인덱스입니다. msdn.microsoft.com/en-us/library/xsy6k3ys(v=vs.84).aspx
— Chris

1
for argument : shortcut.Arguments = "Seta Map mp_crash"; stackoverflow.com/a/18491229/2155778
— Zolfaghari

7
Environment.SpecialFolders.System-존재하지 않습니다 ... Environment.SpecialFolder.System-작동합니다.
— JSWulf

반드시 Microsoft.CSharp를 참조로 추가해야합니다.
— l1nuxuser

76

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);
    }
}

응용 프로그램 바로 가기

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);
    }
}

또한이 예를 확인하십시오 .

일부 API 특정 기능을 사용하려면 COM interop을 통해 IShellLink interface뿐만 아니라 를 사용하는 것이 좋습니다 IPersistFile interface.

다음은 필요한 작업과 샘플 코드를 자세히 설명하는 기사입니다.


위의 내용은 잘 작동합니다. 하지만 DllImport ( "coredll.dll")] 같은 일부 API 함수를 통해 바로 가기를 만들고 싶습니다. public static extern int SHCreateShortcut (StringBuilder szShortcut, StringBuilder szTarget);
— Vipin Arora

@Vipin 왜? 위의 솔루션 중 어느 것이 충분하지 않은 이유가 있습니까?
— alex

8
하찮은 일에 속 태우고 다음 사용 블록의 종료가 당신을 위해 그것을 알아서해야 당신이 플러시 () 라인을 제거 할 수 있습니다
— Newtopian

3
이 방법에 많은 문제가 있습니다 ... Windows는 바로 가기 정의를 어딘가에 캐시하는 경향이 있습니다 ... 이와 같은 바로 가기를 만들고 삭제 한 다음 이름은 같지만 URL이 다른 하나를 만듭니다 ... 가능성은 창입니다 바로 가기를 클릭하면 이전에 삭제 된 URL이 열립니다. 아래 Rustam의 답변 (.url 대신 .lnk 사용)이이 문제를 해결했습니다
— TCC

1
멋진 대답입니다. .lnk 파일을 사용할 때 처리해야하는 끔찍한 COM 배관보다 훨씬 낫습니다.
— James Ko

61

다음은 외부 COM 개체 (WSH)에 의존하지 않고 32 비트 및 64 비트 프로그램을 지원하는 코드입니다.

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-작동하지 않는 것은 무엇입니까? Windows 8 x64에서 테스트했으며 작동합니다.
— Simon Mourier 2013 년

또한 Win8 x64를 실행하고 위의 코드 샘플을 그대로 복사하면 바탕 화면에 경로없이 아이콘이 생성됩니다. 링크를 실행하면 데스크톱에 대한 탐색기가 열립니다. 이것은 ShellLink.cs에서 발생했지만 Windows XP / 2003에서 발생한 유사한 문제입니다. 모든 Windows 버전에서 확실히 작동하는 유일한 예는 Rustam Irzaev가 WSHOM을 사용하는 것이 었습니다. "이것은 매우 유망했지만 Windows 8에서 잘못된 바로 가기를 만듭니다"
— BrutalDev

Windows 8.1 x64에서 작동하도록 설정했지만 지금 여기에 제공된 코드에는 IPersistFile에 대한 정의가 없습니다. 나는 그것을 작동시키기 위해 ShellLink.cs 게시물 에서 복사해야 했습니다.
— Walter Wilfinger 2014

이것이 작동하지 않는 명백한 이유를 보지 못했습니다. 어쨌든, IPersistFile은 System.Runtime.InteropServices.ComTypes에서 즉시 사용할 수 있습니다
— Simon Mourier 2014

1
이 솔루션은 SetIconLocation32 비트 실행 파일이있는 64 비트 Windows 10에서 올바른 아이콘을 설정하지 않습니다 . 해결책은 여기에 설명되어 있습니다. stackoverflow.com/a/39282861 그리고 다른 모든 Windows 8과 동일한 문제라고 생각합니다. 64 비트 Windows의 32 비트 exe 파일과 관련이있을 수 있습니다.
— Maris B.

26

이 ShellLink.cs 클래스를 사용하여 바로 가기를 만들 수 있습니다 .

데스크탑 디렉토리를 얻으려면 다음을 사용하십시오.

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

또는 Environment.SpecialFolder.CommonDesktopDirectory모든 사용자를 위해 작성 하는 데 사용하십시오.


6
@Vipin : 솔루션이 효과가있는 경우 추천하는 것이 일반적입니다. 또한 최상의 솔루션을 선택하고 문제에 대한 답으로 받아 들여야합니다.
— Thorarin

기존 exe를 lnk 파일로 덮어 씁니다. Win10에서 테스트되었습니다.
— zwcloud

@zwcloud이 코드는 아무것도하지 않기 때문에 아무 것도 덮어 쓰지 않습니다. 바로 가기로 작업하는 데 사용할 클래스와 메서드를 알려주는 것뿐입니다. 코드가 자신의 exe를 덮어 쓰는 경우. 실제로 lnk 파일을 만드는 방법을 살펴보고 exe를 파괴하는 이유를 확인합니다.
— Cdaragorn

15

추가 참조없이 :

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();
}
}

바탕 화면에 바로 가기를 만들려면 :

    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

나는 단순히 내 앱에 사용합니다.

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();
    }

바로 사용할 수 있습니다. 복사하여 붙여 넣기
— 만하면

9

사용 ShellLink.cs를 쉽게 바로 가기를 만들 vbAccelerator에!

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
해당 링크는 현재 작동하지 않지만 여기 에서 보관 된 버전을 찾을 수 있습니다 .
— pswg

7

내 코드는 다음과 같습니다.

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

편집하다: 이 솔루션을 더 이상 권장하지 않습니다. Windows 스크립팅 엔진을 사용하는 것보다 더 좋은 방법이 아직 없다면 최소한 메모리에 일반 텍스트 스크립트를 만드는 대신 엔진을 직접 호출하는 @Mehmet의 솔루션을 사용하십시오.

VBScript를 사용하여 바로 가기를 생성했습니다. p / Invoke, COM Interop 및 추가 DLL이 필요하지 않습니다. 다음과 같이 작동합니다.

  • CreateShortcut C # 메서드의 지정된 매개 변수를 사용하여 런타임에 VBScript 생성
  • 이 VBScript를 임시 파일에 저장
  • 스크립트가 완료 될 때까지 기다립니다.
  • 임시 파일 삭제

여기 있습니다 :

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

여기에 도움이되는 주석이있는 (테스트 된) 확장 메서드가 있습니다.

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();
        }
    }
}

그리고 사용 예 :

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

첫 번째 매개 변수는 exe 이름 (현재 디렉토리에 있음)을 설정합니다. 두 번째 매개 변수는 "시작 위치"폴더이고 세 번째 매개 변수는 바로 가기 설명입니다.

이 코드 사용의 예

링크의 명명 규칙은 수행 할 작업에 대한 모호성을 남기지 않습니다. 링크를 테스트하려면 두 번 클릭하십시오.

최종 참고 : 애플리케이션 자체 (타겟)에는 ICON 이미지가 연결되어 있어야합니다. 링크는 exe 내에서 ICON을 쉽게 찾을 수 있습니다. 대상 응용 프로그램에 둘 이상의 아이콘이있는 경우 링크의 속성을 열고 아이콘을 exe에있는 다른 아이콘으로 변경할 수 있습니다.


.GetFolderPath ()가 존재하지 않는다는 오류 메시지가 표시됩니다. XFile.Delete와 동일합니다. 내가 무엇을 놓치고 있습니까?
— RalphF

여기서 오류가 발생합니까? Environment.SpecialFolder.Startup.GetFolderPath ();
— John Peters

2

바로 가기를 만들기 위해 "Windows 스크립트 호스트 개체 모델"참조를 사용합니다.

프로젝트 참조에 "Windows 스크립트 호스트 개체 모델"추가

특정 위치에 바로 가기를 만들려면 :

    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

IWshRuntimeLibrary를 사용하여 Rustam Irzaev의 답변을 기반으로 래퍼 클래스를 만들었습니다.

IWshRuntimeLibrary-> 참조-> COM> Windows 스크립트 호스트 개체 모델

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

Windows Vista / 7 / 8 / 10의 경우 대신를 통해 심볼릭 링크를 만들 수 있습니다 mklink.

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

또는 CreateSymbolicLinkP / Invoke를 통해 호출하십시오.


이것은 바로 가기와 관련이 없습니다.
— Matt
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.