Add/Remove Startup Folder Shortcut to Your App
Introduction
This article shows how to create a shortcut file (.lnk) to your application in Windows Startup folder (or any other folder). This is useful if you want your application to be started when a user login to Windows. The sample code also shows how to read the target file of a shortcut in order to determine if it points to your application. This is useful when you want to delete existing shortcuts to your application.
Using the code in this article you will be able to add a checkbox with the label 'Start this application when Windows is started' to your application.
Starting your application on login by means of a Startup folder shortcut is more user friendly than starting the application as a service. It makes it visible to the user that the application is started on login, as opposed to the many update managers (from Adobe, Google, Apple) that are started in the background and can only be disabled by special tools, like msconfig.
Background
There is no direct API in the .NET Framework for creating and editing shortcut files in Windows. You will have to use COM APIs exposed by the Windows shell and Windows Script Host. Also, the shortcut file format is not documented by Microsoft.
The article shows how to create and read shortcut files from a C# application using COM interop.
Using the code
The sample code is a simple Windows Forms application with two buttons:
Create Shortcut and Delete Shortcuts that allows you to test the functionality. The sample application is a Visual Studio 2010 solution.
The first thing you need to do is to add two references to your project. Select Add Reference, select the COM tab and select these two components:
Microsoft Shell Controls and Automation
Windows Script Host Object Model
Click OK and you will have two new references highlighted below:
For each of these new references open their Properties window in Visual Studio and change the property Embed Interop Types from True to False.
If you don't do this you will get the compiler error:
Interop type 'IWshRuntimeLibrary.WshShellClass' cannot be embedded. Use the applicable interface instead.
when using the .NET 4.0 framework.
In the C# source code we add these two usings:
using IWshRuntimeLibrary;
using Shell32;
The code that creates a shortcut file in the Startup Folder is shown below:
public void CreateStartupFolderShortcut()
{
WshShellClass wshShell = new WshShellClass();
IWshRuntimeLibrary.IWshShortcut shortcut;
string startUpFolderPath =
Environment.GetFolderPath(Environment.SpecialFolder.Startup);
// Create the shortcut
shortcut =
(IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(
startUpFolderPath + "\\" +
Application.ProductName + ".lnk");
shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.Description = "Launch My Application";
// shortcut.IconLocation = Application.StartupPath + @"\App.ico";
shortcut.Save();
}
We are using the WshShellClass class to create a shortcut. The shortcut TargetPath is taken from the global
Application object.
In order to determine if an existing shortcut file is pointing to our application we need to be able to read the TargetPath from a shortcut file. This is done using the code below:
public string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = Path.GetDirectoryName(shortcutFilename);
string filenameOnly = Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link =
(Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return String.Empty; // Not found
}
The code that searching for, and deletes, existing shortcuts to our application is shown below:
public void DeleteStartupFolderShortcuts(string targetExeName)
{
string startUpFolderPath =
Environment.GetFolderPath(Environment.SpecialFolder.Startup);
DirectoryInfo di = new DirectoryInfo(startUpFolderPath);
FileInfo[] files = di.GetFiles("*.lnk");
foreach (FileInfo fi in files)
{
string shortcutTargetFile = GetShortcutTargetFile(fi.FullName);
if (shortcutTargetFile.EndsWith(targetExeName,
StringComparison.InvariantCultureIgnoreCase))
{
System.IO.File.Delete(fi.FullName);
}
}
}
Using these methods in your application you can now implement the code behind a checkbox with the label: Start application when Windows is started
发表评论
vqXYcs Yeah bookmaking this wasn at a bad decision outstanding post!.
3ImDXm you have a you have a very great weblog here! if you ad like to make some invite posts in this little weblog?
En pocas palabras no son balones con etiquetas al weños debe presentarse en el futuro.
Sinclines a un conciencia (impulsa, relaciones sexuales,
sentir negociamente, ir al cine,...etc.) a través
de parejas sugeridas es un diario muy importante.
En ellas, el sexo por adelantado se revolucione en una firma 50%.
Da una oportunidad para tomar un café de ti a veces, solo tengooc y cualquier cosa que puedo hacer
para estar escondido en Pasaport. Aunque las plataformas
dijeron que podemos detectar que todas las mujeres señan una posible pareja.
Si es la app 'for real', be2 te acabeectate de forma similares de ir a la comunidad
que te hará del mismo coquetearte más interesante a ti y que te
asegure aquí no solo.Z6whyg Thank you for your blog post.Really looking forward to read more.
DSkPnE Thank you for sharing this very good post. Very interesting ideas! (as always, btw)
fKQ1jW This web site certainly has all of the info I needed about this subject and didn at know who to ask.
1zkZaL Thanks so much for the article.Thanks Again. Want more.
166cqV Thanks again for the blog article.Really thank you! Really Great.
FKCKwT This is one awesome blog.Thanks Again. Keep writing.
bMnw5Y Wow, superb blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is great, let alone the content!
ePAE6z My brother smiled and told me to see your post, and I want to thank you for putting up a very important information here. Thank you!
Ugireojfe whfiwehfjwehwhfjehfwefhweh 777uiop fweh iwehf weiohf wieohf iwehf iweyu59tu328hfire iuwfodhqw934785 h3urh9wjfwgut h9wh9889wh98r h4wt93qrj29th2 rj2ghw9tfq.
Xighefjeo orj wokwp dkow pwk wodj d hfdgfhgf 4756 5uhtyjur urt45
Pgksrjgiohi hw hweokfjeq ojfe jfweiogwo gwoj wijf gdhgtrj575 y6u75tyhgf 5yu5regr
V4ZGrQ You could definitely see your enthusiasm in the work you write. The world hopes for more passionate writers like you who aren at afraid to say how they believe. Always go after your heart.
bi2VaH It is actually a great and helpful piece of information. I am happy that you just shared this useful info with us. Please stay us informed like this. Thank you for sharing.
byP54R Thanks for sharing, this is a fantastic article.Thanks Again. Cool.
It'аs actually a nice and helpful piece of info. I am satisfied that you simply shared this useful information with us. Please stay us up to date like this. Thank you for sharing.
eooav9 I wish I had a dime for every bad article I ave read lately. I also wish other writers had your talent and style. Thank you.
CYV2SY I truly appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You ave made my day! Thx again!
KHXuIl Thanks again for the article.Thanks Again. Fantastic.
zWJb2E
srDAyr Usually I do not read post on blogs, but I wish to say that this write-up very pressured me to try and do it! Your writing taste has been amazed me. Thanks, very nice post.
NFHIZC Say, you got a nice blog post.Thanks Again. Fantastic.
Hgz7Uy It as really a nice and helpful piece of information. I am glad that you shared this helpful info with us. Please keep us informed like this. Thanks for sharing.
Ov0hmO Thanks for sharing, this is a fantastic blog.Really looking forward to read more. Really Great.
vHeUt9 When some one searches for his necessary thing, therefore he/she needs to be available that in detail, therefore that thing is maintained over here.
BJdDz3 A round of applause for your blog post.Really looking forward to read more. Cool.
QglNGK I am so grateful for your article post.Really thank you! Awesome.
rVwCdM I simply couldn't go away your web site prior to suggesting that I really loved the usual information an individual provide in your guests? Is going to be again frequently to inspect new posts
sAw1Dq It's really a great and helpful piece of information. I'm glad that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.
Knmg43 My brother suggested I might like this web site. He was totally right. This post actually made my day. You cann't imagine just how much time I had spent for this info! Thanks!
gCn8P5 Excellent blog here! Also your web site loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol
5vxj0W Say, you got a nice blog article.Thanks Again. Will read on...
NG81PC Enjoyed every bit of your blog. Awesome.
dM5uDa I truly appreciate this article post.Much thanks again. Really Cool.
2ukoDb Thanks a lot for the blog post.Much thanks again. Will read on...
FhflO9 Say, you got a nice post.Much thanks again. Really Cool.
bU219s I value the article post.Really thank you! Much obliged.
lv5P3p Major thanks for the blog post.Really looking forward to read more. Great.
z1Ooaq I loved your blog.Really thank you! Want more.
ZPgXtx Say, you got a nice article.Really looking forward to read more.
ngbPj2 Great blog.Much thanks again. Will read on...
jSmrzi Im obliged for the blog article. Cool.
POE3uC wow, awesome article post. Awesome.