Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Run C# application on user logon (Windows Forms)

0.00/5 (No votes)
28 Oct 2014 1  
A tip about how to run a Windows Forms application in C# on user logon

Introduction 

Sometimes it is necessary to run a program on user logon. In this tip, I will learn you how to run a C# program automatically in Windows Forms.

Using the code 

First, we need to know the location of the Startup folder.  To do that, we use this code:

string startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

Now, we need to create the shortcut. To do that, we need to add a reference to the Windows ScriptHost Object Model. If you use Visual C#, you can see on this pictures how to add the reference:

And then, choose the Windows Script Host Object Model in the tabpage 'COM':

Now, add this using namespace statement at the top of your code file:

using IWshRuntimeLibrary;

Then, create the shortcut: 

WshShell shell = new WshShell();
string shortcutAddress = startupFolder + @"\MyStartupShortcut.lnk";
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "A startup shortcut. If you delete this shortcut from your computer, LaunchOnStartup.exe will not launch on Windows Startup"; // set the description of the shortcut
shortcut.WorkingDirectory = Application.StartupPath; /* working directory */
shortcut.TargetPath = Application.ExecutablePath; /* path of the executable */
shortcut.Save(); // save the shortcut 

Optionally, you can set the arguments of the shortcut:

shortcut.Arguments = "/a /c";

Do that before you save the shortcut. Setting the arguments is not required; do it only if your program needs that.

But don't use a name such as "MyStartupShortcut.lnk", because there is a risk that other programs use that name, and that you overwrite that shortcut.  Use a shortcut name such as "Clock.lnk" if you've a clock application, or "TcpServer.lnk" if you've a TCP/IP application.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here