डेस्कटॉप पर एक शॉर्टकट बनाएं


106

मैं कुछ EXE फ़ाइल को इंगित करने वाला एक शॉर्टकट बनाना चाहता हूं, डेस्कटॉप पर, .NET फ्रेमवर्क 3.5 का उपयोग करके और एक आधिकारिक विंडोज एपीआई पर भरोसा करता है। मैं उसे कैसे कर सकता हूँ?


1
रुस्तम इरेज़ेव से विंडोज स्क्रिप्ट होस्ट ऑब्जेक्ट मॉडल का उपयोग करना उचित शॉर्टकट के लिए एकमात्र विश्वसनीय है। आयुष: यह तकनीक गर्म कुंजी और विवरण जैसी सुविधाओं का एक गुच्छा याद करती है। थोरिन: शेललिंक ज्यादातर मामलों में अच्छा काम करता है, लेकिन विशेष रूप से यह विंडोज एक्सपी में काम नहीं करता है और अवैध शॉर्टकट बनाता है। साइमन Mourier: यह बहुत आशाजनक गया था, लेकिन Windows 8 में अमान्य शॉर्टकट बना देता है
BrutalDev

साइमन मूरियर का जवाब यहां सबसे अच्छा जवाब है। शॉर्टकट बनाने का एकमात्र सही और बुलेट प्रूफ तरीका उसी API का उपयोग करना है जिसे ऑपरेटिंग सिस्टम उपयोग करता है और यह IShellLink इंटरफ़ेस है। विंडोज स्क्रिप्ट होस्ट का उपयोग न करें या वेब लिंक न बनाएं! साइमन मूरियर दिखाता है कि कोड की 6 लाइनों के साथ यह कैसे करना है। किसी को भी, जिसे इस पद्धति से समस्या थी, SURELY ने अमान्य रास्तों को पारित कर दिया। मैंने विंडोज एक्सपी, 7 और 10 पर उसके कोड का परीक्षण किया। 32/64 बिट विंडोज के साथ समस्याओं से बचने के लिए अपने एप्लिकेशन को "किसी भी सीपीयू" के रूप में संकलित करें जो प्रोग्राम फाइलों, एट अल के लिए अलग-अलग फ़ोल्डर्स का उपयोग करते हैं।
एल्म्यू

जवाबों:


120

अतिरिक्त विकल्पों जैसे हॉटकी, विवरण आदि के साथ।

सबसे पहले, प्रोजेक्ट > संदर्भ जोड़ें > COM > विंडोज स्क्रिप्ट होस्ट ऑब्जेक्ट मॉडल।

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
यह वास्तव में मेरे लिए करीब था। मुझे शॉर्टकट पर "वर्कडायरेक्टरी" संपत्ति में .exe की निर्देशिका को जोड़ने की आवश्यकता थी। (shortcut.WorkingDirectory) +1
शमूएल

4
आइकन इंडेक्स (IconLocation में) निर्दिष्ट करने के लिए, "path_to_icon_file, #" जैसे मान का उपयोग करें, जहां # आइकन इंडेक्स है। देखें msdn.microsoft.com/en-us/library/xsy6k3ys(v=vs.84).aspx
क्रिस

1
तर्क के लिए: shortcut.Arguments = "सेटा मैप 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);
    }
}

इस उदाहरण को भी देखें ।

यदि आप कुछ एपीआई विशिष्ट कार्यों का उपयोग करना चाहते हैं तो आप (COM इंटरॉप के माध्यम से) IShellLink interfaceभी उपयोग करना चाहेंगे IPersistFile interface

यहां एक लेख है जो विस्तार से जाता है कि आपको क्या करने की आवश्यकता है, साथ ही साथ नमूना कोड भी।


ये ऊपर ठीक काम कर रहे हैं। लेकिन मैं कुछ एपीआई फ़ंक्शन जैसे DllImport ("coredll.dll")] के माध्यम से शॉर्टकट बनाना चाहता हूं; सार्वजनिक स्थैतिक बाहरी int SHCreateShortcut (StringBuilder szShortcut, StringBuble szTarget);
विपिन अरोड़ा

@ विपिन क्यों? क्या कोई कारण है कि उपरोक्त समाधानों में से कोई भी पर्याप्त अच्छा नहीं है?
एलेक्स

8
नाइटपंटिंग: आप फ्लश () लाइन को हटा सकते हैं क्योंकि
ब्लॉकिंग

3
मुझे इस पद्धति से बहुत सी समस्याएं हुई हैं ... विंडोज़ ने शॉर्टकट परिभाषा को कहीं कैश करने की प्रवृत्ति दी है ... इस तरह से एक शॉर्टकट बनाएं, इसे हटाएं, फिर एक ही नाम से एक अलग URL बनाएं लेकिन संभावनाएं हैं विंडोज़ शॉर्टकट क्लिक करने पर पुराना हटा दिया गया URL खुल जाएगा। रुस्तम का जवाब नीचे (उपयोग .lnk के बजाय .ll) ने मेरे लिए इस समस्या को हल किया
TCC

1
बहुत बढ़िया जवाब। जब आप .lnk फ़ाइलों का उपयोग करते हैं तो आपको निपटने के लिए होने वाली भयानक COM प्लंबिंग से बहुत बेहतर होता है।
जेम्स

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 - क्या काम नहीं करता है? मैंने इसे विंडोज 8 x 64 पर परीक्षण किया है और यह काम करता है।
साइमन मूरियर

इसके अलावा Win8 x64 को चलाने पर, ऊपर दिए गए कोड नमूने की नकल की जाती है, यह बिना किसी पथ के साथ मेरे डेस्कटॉप पर एक आइकन बनाता है। लिंक से बाहर निकलते ही डेस्कटॉप पर एक्सप्लोरर खुल जाता है। यह एक समान मुद्दा है जो मैंने शेललिंक के साथ किया था। लेकिन विंडोज एक्सपी / 2003 में। एकमात्र उदाहरण जो सभी विंडोज़ संस्करणों में निश्चित रूप से काम करता है, रुस्तम इरेज़ेव ने WSHOM का उपयोग किया था जैसा कि मैंने अपनी टिप्पणी में मुख्य प्रश्न का उल्लेख किया है: "यह बहुत ही आशाजनक था, लेकिन विंडोज 8 में अमान्य शॉर्टकट बनाता है"
क्रूरडाल

मुझे यह विंडोज 8.1 x 64 पर काम करने के लिए मिला है, लेकिन यहाँ दिए गए कोड की अब IPersistFile के लिए परिभाषा नहीं है। मैं उस पर काम करने के लिए ShellLink.cs पोस्ट से कॉपी करना था ।
वाल्टर विल्फिंगर

मैं कोई ठोस कारण नहीं देखता कि यह काम क्यों नहीं करेगा। वैसे भी, IPersistFile System.unt.InteropServices.ComTypes में आउट-ऑफ-द-बॉक्स उपलब्ध है
शमौन Mourier

1
यह समाधान SetIconLocation32-बिट निष्पादन योग्य 64-बिट विंडोज 10 का उपयोग करके सही आइकन सेट नहीं करता है । समाधान यहाँ वर्णित है: stackoverflow.com/a/39282861 और मुझे यह भी संदेह है, कि विंडोज 8 के साथ भी यही समस्या है, अन्य सभी को नुकसान हो रहा है। यह 64-बिट विंडोज पर 32-बिट exe फ़ाइलों से संबंधित हो सकता है।
मैरिस बी।

26

शॉर्टकट बनाने के लिए आप इस ShellLink.cs वर्ग का उपयोग कर सकते हैं ।

डेस्कटॉप निर्देशिका प्राप्त करने के लिए, का उपयोग करें:

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

या Environment.SpecialFolder.CommonDesktopDirectoryसभी उपयोगकर्ताओं के लिए इसे बनाने के लिए उपयोग करें।


6
@ विपिन: यदि कोई समाधान आपके लिए काम करता है, तो इसे बढ़ाने के लिए प्रथागत है। साथ ही, आपको सबसे अच्छा समाधान चुनना चाहिए और इसे अपनी समस्या के उत्तर के रूप में स्वीकार करना चाहिए।
थोरिन

यह lnk फ़ाइल के साथ मौजूदा exe को अधिलेखित कर देगा। 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();
    }

बॉक्स से बाहर काम करता है, बस इसे कॉपी-पेस्ट करें
rluks

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
यह लिंक अब मृत हो गया है, लेकिन आप यहां इसका संग्रहीत संस्करण पा सकते हैं ।
१g

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

संपादित करें: मैं अब इस समाधान की सिफारिश नहीं करता हूं। यदि विंडोज स्क्रिप्टिंग इंजन का उपयोग करने की तुलना में अभी भी कोई बेहतर तरीका नहीं है, तो कम से कम @ 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");

1 parm exe नाम सेट करता है (वर्तमान निर्देशिका में पाया गया) 2 parm "स्टार्ट इन" फोल्डर है और 3rd parm शॉर्टकट विवरण है।

इस कोड का उपयोग करने का उदाहरण

लिंक का नामकरण सम्मेलन कोई अस्पष्टता नहीं छोड़ता है कि यह क्या करेगा। लिंक का परीक्षण करने के लिए इसे डबल क्लिक करें।

अंतिम नोट: आवेदन स्वयं (लक्ष्य) के पास एक ICON छवि होनी चाहिए। लिंक आसानी से exe के भीतर ICON का पता लगाने में सक्षम है। यदि लक्ष्य एप्लिकेशन में एक से अधिक आइकन हैं, तो आप लिंक के गुणों को खोल सकते हैं और आइकन को एक्स में पाए गए किसी अन्य में बदल सकते हैं।


मुझे एक त्रुटि संदेश मिल रहा है कि .GetFolderPath () मौजूद नहीं है। XFile.Delete के लिए भी। मैं क्या खो रहा हूँ?
राल्फ एफएफ़

क्या यहाँ त्रुटि होती है? Environment.SpecialFolder.Startup.GetFolderPath ();
जॉन पीटर्स

2

मैं शॉर्टकट बनाने के लिए "विंडोज स्क्रिप्ट होस्ट ऑब्जेक्ट मॉडल" संदर्भ का उपयोग करता हूं।

प्रोजेक्ट संदर्भ के लिए "विंडोज स्क्रिप्ट होस्ट ऑब्जेक्ट मॉडल" जोड़ना

और विशिष्ट स्थान पर शॉर्टकट बनाने के लिए:

    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 के उपयोग के साथ रुस्तम इरेज़ेव के उत्तर के आधार पर मैंने एक रैपर क्लास बनाई है।

IWshRuntimeLibrary -> संदर्भ -> COM> विंडोज स्क्रिप्ट होस्ट ऑब्जेक्ट मॉडल

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

विंडोज विस्टा / 7/8/10 के लिए, आप इसके बजाय एक सिमलिंक बना सकते हैं mklink

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

वैकल्पिक रूप से, CreateSymbolicLinkP / Invoke के माध्यम से कॉल करें ।


इसका शॉर्टकट से कोई लेना-देना नहीं है।
मैट
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.