Geekpedia Programming Tutorials






Create shortcuts with a .NET application

This tutorial will show you the code you need to write to have your application create shortcuts to any path (the desktop, startup folder, etc.).

On Friday, June 10th 2005 at 11:57 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.7 with 36 votes)
Contextual Ads
More C# Resources
Advertisement
CreatingShortcuts.zip (56.8 KB)



Creating a shortcut from within a C# Windows application is not as easy as using a method in a namespace of the .NET framework. However, after you'll be reading this tutorial, you'll find that it's not rocket science either. For testing purposes, you can create a Windows Forms applications, and add a button on it: btnShortcut. Double-clicking the button will bring you to the btnShortcut_Click event, where we will write some lines of code that will actually create the shortcut.



But before that, we need to add a reference to Windows Script Host Object Model. To do that, right-click the "References" folder in Solution Explorer and choose "Add Reference". From the COM tab, choose Windows Script Host Object Model. Double click it, and it will be added to the "Selected Components" list:







Now click OK and let's get to coding. You can see in the Solution Explorer that we know have IWshRuntimeLibrary added. So we don't have to write long lines of code, let's add a "using" directive in the Form1.cs file:





using IWshRuntimeLibrary;



Next we shall create WshShell, an object of type WshShellClass:





private WshShellClass WshShell;



Now inside the "click" event of the button, we do the coding:





private void btnShortcut_Click(object sender, System.EventArgs e)

{

// Create a new instance of WshShellClass

WshShell = new WshShellClass();

// Create the shortcut

IWshRuntimeLibrary.IWshShortcut MyShortcut;


// Choose the path for the shortcut

MyShortcut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(@"C:\MyShortcut.lnk");


// Where the shortcut should point to

MyShortcut.TargetPath = Application.ExecutablePath;


// Description for the shortcut

MyShortcut.Description = "Launch My Application";


// Location for the shortcut's icon

MyShortcut.IconLocation = Application.StartupPath + @"\app.ico";


// Create the shortcut at the given path

MyShortcut.Save();

}




Notice that we choosed the path to the current application, as the TargetPath, but you can set the shortcut to point to any file you want:





MyShortcut.TargetPath = @"C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\devenv.exe";




The description of the shortcut is also shown when in the tooltip, when the cursor is over the icon.

Currently, we set the location of the icon for the shortcut to app.ico, located inside the project's Debug folder (Application.StartupPath). app.ico is included in the project.

However, you can always change the path for the icon to something like:





MyShortcut.IconLocation = @"C:\Program Files\Microsoft Office\OFFICE11\REFBAR.ICO";




If you download and run the project, it will create a shortcut to itself (the executable inside bin\Debug directory) in C:\, as can be seen here:



Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Karl on Friday, August 5th 2005 at 04:18 PM

Hi, nice! One question: if i want to use an icon, which is e.g. part of Shell32, how do i select the icon i want to use?
TIA
Karl

by Andrei Pociu on Friday, August 5th 2005 at 04:35 PM

Hello,

You need to extract the icon from Shell32.dll first. The class you can find at <a href="http://www.codeproject.com/csharp/IconHandler.asp" target="_blank">http://www.codeproject.com/csharp/IconHandler.asp</a> will help you do just that. Then after extracting it, you save it (inside your application's path) and assign it using the MyShortcut.IconLocation property.

by Karl on Saturday, August 6th 2005 at 02:50 PM

Thx Andrei for the link. But i wonder, how does Windows do it? Can't imagine it "extracting" and probably then hiding an icon file everytime i make a new link by hand ;-)

by Andrei Pociu on Saturday, August 6th 2005 at 02:58 PM

Good question. Unfortunately I don't know any way of doing this the way Windows does, I'm not even sure if it is possible.

by Karl on Tuesday, August 9th 2005 at 03:34 AM

Andrei,
got it, our guru at Culeplace.com knew the answer. It's simple: add the (zero based) number of your icon to the path: e.g. oLink:IconLocation:= sSystemPath +"\Shell32.dll,8"

by Andrei Pociu on Tuesday, August 9th 2005 at 03:41 AM

Wow, never knew it was that simple :)
Thanks, I'm sure others will find this helpful too.

by Karthik on Thursday, February 2nd 2006 at 09:07 AM

Thank you so much for this wondeful piece of code! you do not know much it helped me although I am using vb.net instead of C#, the most easiest example. I just wondering if anyone knows how to do the same shortcut but to include it in the program menu? Thnak you!

by Andrei Pociu on Thursday, February 2nd 2006 at 12:24 PM

Create the shortcut inside C:\Documents and Settings\Default User\Start Menu\Programs

(you might want to replace Default User with the name of the current user).

Good luck!

by Kostas on Thursday, April 6th 2006 at 03:13 PM

I take an Exception:
Exception occurred. (Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION))

in line:

MyShortcut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(@\"C:\\MyShortcut.lnk\");


why? Help me please..

by Rodel E. Dagumampan on Friday, August 11th 2006 at 02:10 AM

I am trying to use the WshShell but I always get this weird interop error, please advise.

Unable to cast COM object of type \'System.__ComObject\' to class type \'IWshRuntimeLibrary.WshURLShortcutClass\'. COM components that enter the CLR and do not support IProvideClassInfo or that do not have any interop assembly registered will be wrapped in the __ComObject type. Instances of this type cannot be cast to any other class; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface., (NULL), (NULL), (NULL).


1 savedState = stateSaver;

2 base.Install(savedState);

3

4 ConfigurationForm configurator = new ConfigurationForm();

5 if (configurator.ShowDialog() == System.Windows.Forms.DialogResult.OK) {

6 SetupInformation setupInfo = configurator.SetupInformation;

7

8 //TODO : Modify the configuration file

9

10 WshShellClass shell = new WshShellClass();

11 WshURLShortcutClass shortcut;

12

13 shortcut = (WshURLShortcutClass)shell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) + \"\\\\...lnk\");

14 shortcut.TargetPath = setupInfo.RMAddress;

16 shortcut.Save();

17

18 shortcut = (WshURLShortcutClass)shell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) + \"\\\\...lnk\");

19 shortcut.TargetPath = setupInfo.RVAddress;

21 shortcut.Save();

22 } else {

23 base.Rollback(savedState);

24 }

by Shawn on Tuesday, August 22nd 2006 at 02:23 PM

I can't create a shortcut to a folder. It will be treated as a file. why? Thanks!

by IPanera on Thursday, May 24th 2007 at 07:41 AM

I have to modify the code in order to compile it, but just this line:

MyShortcut = (IWshRuntimeLibrary.IWshShortcut) shell.CreateShortcut(@"C:\MyShortcut.lnk");

instead of

MyShortcut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(@"C:\MyShortcut.lnk");

it works fine.
Thanks all

by Nick Pasko on Monday, July 9th 2007 at 07:36 AM

IPanera, you obviously named your WshShellClass 'shell' instead of 'WshShell' ;)

by on Thursday, August 9th 2007 at 04:34 PM

I am a contractor at Microsoft (Redmond). I suggested this technique to the other FTE and they said this method is not very good and better to p/invoke a shell. Just wanted to let you know.

by RE on Thursday, January 10th 2008 at 03:21 PM

OR you could just do it the easy way, eg: http://www.sorrowman.org/c-sharp-programmer/url-link-to-desktop.html

by REM on Thursday, January 10th 2008 at 03:34 PM

That link does it through the file:// protocol, meaning it's getting executed through a browser. So the easy way is NOT the right way.

by JoRo on Saturday, January 12th 2008 at 06:06 PM

Well, it only said the easy way, it didn\\\'t say anything being Right or Wrong, now did it?

And if we are talking about \\\"right\\\" and \\\"wrong\\\", using Windows Script Host Object Model is NOT the right way either. Not in .Net anyway.

by Robert on Wednesday, February 6th 2008 at 03:36 PM

HELP!!!

I am trying to use ur code to help teach how to create a folder shortcut which i have done by simply changing the target path but unfortunately it comes up and askes after selecting the shortcut to select a program to use so the shortcut isnt set up correctly can anyone assist

by bagamabga on Thursday, September 18th 2008 at 04:16 AM

visual basic script to create shortcut on users desktop


Dim objShell

Set objShell = WScript.CreateObject("WScript.Shell")
strDesktopFolder = objShell.SpecialFolders("Desktop")
para = objShell.SpecialFolders("Desktop")
Set objShortCut = objShell.CreateShortcut(strDesktopFolder

by Mehdi on Tuesday, September 30th 2008 at 05:12 AM

Note: It's also important to set the "WorkingDirectory" property of the shortcut if u have relative paths in your application.

by karthi on Tuesday, December 30th 2008 at 11:15 PM

this wshshell thing goes well to create shortcuts
in windowsxp when i try to use the same code in
windows2000 it doesnt supports.it raises an exception.

any suggestions

by karthi on Tuesday, December 30th 2008 at 11:18 PM

and one more thing im using c#.(it is possible to create shortcuts in xp

by Aravind on Thursday, January 22nd 2009 at 09:20 AM

Dear All,

when i tried creating shortcut as shown above, i am getting this below error.
-----
System.Runtime.InteropServices.COMException was unhandled
Message="Exception occurred. (Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION))"
Source="Interop.IWshRuntimeLibrary"
ErrorCode=-2147352567
StackTrace:
at IWshRuntimeLibrary.WshShellClass.CreateShortcut(String PathLink)
at WinApp1.frmMain.CreateShortCut() in C:\WinApp1\WinApp1\Form1.cs:line 87
at WinApp1.frmMain.btnStartup_Click(Object sender, EventArgs e) in C:\WinApp1\WinApp1\Form1.cs:line 105
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message

by Aravind on Thursday, January 22nd 2009 at 09:32 AM

All,
Thanks again. The above issue has been solved. this is the problem from my side. i didnt give the link filename as <some_path> "\\<somename.lnk>";

this part i missed out.

It works great!!

by karthik on Friday, February 6th 2009 at 06:49 AM

hi,

have you ever tried this program in windows2000,if u did u will get a error,the above code goes well in xp but not the same case in 2000.awaiting ur reply.

by karthik on Friday, February 6th 2009 at 06:58 AM

hi karthik again

can anyone tell me hw to write a code in c# for creating shortcuts which must work in win2000

by chris on Saturday, February 7th 2009 at 02:58 AM

use the Enviroment Namespace to find out what operating system your running and modify the WSH commands accordingly win2k has wsh too but its an older version even so this method works you may have to write a few more lines.

by vin on Tuesday, February 24th 2009 at 01:15 AM

the shortcut description - can it be localized so that it displays in the language of the host OS/user?

by vin on Tuesday, February 24th 2009 at 01:15 AM

the shortcut description - can it be localized so that it displays in the language of the host OS/user?

by raj on Tuesday, May 5th 2009 at 12:00 PM

Hi
I would like to execute this shortcut from C# program. Pls advise ?

Thanks
Raj

by Vibha on Tuesday, May 5th 2009 at 12:06 PM

Hi
I would like to execute this shortcut from C# program. Pls advise ?

Thanks
Vibha

by mohit on Thursday, May 7th 2009 at 10:07 PM

when i tried creating shortcut as shown above, i am getting this below error.
pls give the solution
-----



System.Runtime.InteropServices.COMException (0x80020009): Exception occurred. (Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION))
at IWshRuntimeLibrary.WshShellClass.CreateShortcut(String PathLink)
at WindowsApplication1.Form1.btnShortcut_Click(Object sender, EventArgs e) in D:\Documents and Settings\Administrator\Local Settings\Application Data\Temporary Projects\WindowsApplication1\Form1.cs:line 33
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message

by Alex on Friday, June 12th 2009 at 11:48 PM

Vibha and Raj:

To execute the shortcut you just created, try this:

/*Create a string of the filepath that you will execute */
string filepathtoexecute = "filepath";
/*now call that path with the Process class and its start method */
Process.Start(filepathtoexecute);


Also i have question of my own, how would you target the locations such as My computer and Recycle Bin?

Thanks,
Alex


by Ofir on Tuesday, July 21st 2009 at 06:46 AM

Hi all,
Does anybody know how to create advertised shortcut? meaning user can NOT edit shortcut via Properties window

thx

by Ivan on Friday, August 21st 2009 at 04:02 AM

Thanks..

by Sean on Saturday, September 5th 2009 at 04:23 PM

For those with HRESULT: 0x80020009 error, you must use the .lnk extension when creating the shortcut filename. The .lnk will be hidden in your explorer but the rest of the filename will show. Therefore, if you wanted to make a shortcut to a file hello.txt and wanted the shortcut to have the same name, then you would name it hello.txt.lnk in the code, and it will show up as hello.txt in file explorer

by e.Lock Val on Friday, November 20th 2009 at 06:58 AM

thanks, helped me like a charm

by bjorn on Friday, November 20th 2009 at 08:40 AM

0x80020009 (DISP_E_EXCEPTION)

and im calling it name.exe.ink
...

by bjorn on Friday, November 20th 2009 at 08:47 AM

0x80020009 (DISP_E_EXCEPTION)

and im calling it name.exe.ink
...
and guess what, stupid me its "Lnk" not "Ink" :p

thanks though :)

by Joel on Sunday, March 21st 2010 at 01:29 PM

Is ther an error in your code on the following line?
WshShell = new WshShellClass();


In my C#k project, WshShell is a type. There is no variable for WshShellClass().

This is what I'm going to use:
WshShellClass shell = new WshShellClass();

by ikpil on Sunday, April 4th 2010 at 10:15 PM

this code is very good.
Thanks :)

by RoyBoy on Saturday, May 8th 2010 at 09:14 PM

Code works fine in debug, but when I copy the .exe file from the release folder to my desktop and run it, I get an error that says it can't find Interop.IWshRuntimeLibrary.dll. So I copied that file from the release folder to the desktop too, and no longer get the error. But I don't want to have to drag this extra file around with my program. How can I include it in the build so that I have a standalone program?

by Alex on Sunday, May 9th 2010 at 08:45 AM

RoyBoy:

Include the dll file in your applications Resources file and have your program write the dll to the same directory as your executable when it first runs.

by RoyBoy on Sunday, May 9th 2010 at 07:29 PM

Thanks, Alex

by RoyBoy on Sunday, May 9th 2010 at 09:36 PM

Update... Just happened to find this great utility from Microsoft that can merge multiple assemblies into one. ILMerge. Google it. Worked smoothly for me and gave me a single standalone executable.

by Pablo on Wednesday, June 16th 2010 at 06:37 PM

Can i add a shortcut into a picturebox in my program??

by Alex on Friday, June 18th 2010 at 08:14 PM

Pablo:

What do you mean by add a shortcut to a picturebox?


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons