How to autostart a c sharp application when booting windows? - c#

I have a solution with two project files in it. One executable is a windows form application and the other one is a console application. Both executables perform different tasks, however, both need to be run at the same time (only the windows form has to be started). Therefore I added following code to my windows form application:
RegistryKey rkApp =
Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
true);
public Form1()
{
if (rkApp.GetValue("somename") == null)
{
rkApp.SetValue("somename", Application.ExecutablePath.ToString());
}
When I now restart the PC, everything's gone... Any ideas why this problem is turning up? Thank you!
P.S.: I'm a complete beginner, please be nice :)

You need to create a Windows Service Project and install with a service in windows.

If you have a .EXE file, you can add it to Start Up Programms using MSCONFIG from CMD, it's a Non-Coded Solution, but if you want it to attach to register as a service, then create a Windows Service Project.

Use REGEDIT to confirm that the 'somename' was added, also your code has the problem that it only checks 'somename' was previously set, not that the path is correct. If you ran the code in a different path during testing, it would never be updated. Also RegistryKey should be closed after you are finished with it. By rkApp.Close() or by 'using'.
using (RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
if (rkApp.GetValue("somename") != Application.ExecutablePath.ToString())
{
rkApp.SetValue("somename", Application.ExecutablePath.ToString());
}
}
You say only the form needs to be launched, does the form run the console? What happens?
Anothing possibility is when running a program by the registry, the 'Current Directory' is 'C:\Windows\System32' and not the application path. If you are using code such as:
File.ReadAllText('SomeFile.txt');
It would try opening C:\Windows\System32\SomeFile.txt and not \YourApp\SomeFile.txt, which can be fixed by:
// Reliably get the .EXE directory, this works for both Form and Console applications:
var AssemblyDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
// Option 1 is set on load:
Directory.SetCurrentDirectory(AssemblyDirectory);
// Option 2 is use full paths for anything opening files:
File.ReadAllText(AssemblyDirectory + "\\SomeFile.txt");

Related

How to manage different Programs At the same time in c# [duplicate]

I have a small application with a CheckBox option that the user can set if they want the app to start with Windows.
My question is how do I actually set the app to run at startup.
ps: I'm using C# with .NET 2.0.
Thanks to everyone for responding so fast.
Joel, I used your option 2 and added a registry key to the "Run" folder of the current user.
Here's the code I used for anyone else who's interested.
using Microsoft.Win32;
private void SetStartup()
{
RegistryKey rk = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (chkStartUp.Checked)
rk.SetValue(AppName, Application.ExecutablePath);
else
rk.DeleteValue(AppName,false);
}
Several options, in order of preference:
Add it to the current user's Startup folder. This requires the least permissions for your app to run, and gives the user the most control and feedback of what's going on. The down-side is it's a little more difficult determining whether to show the checkbox already checked next time they view that screen in your program.
Add it to the HKey_Current_User\Software\Microsoft\Windows\CurrentVersion\Run registry key. The only problem here is it requires write access to the registry, which isn't always available.
Create a Scheduled Task that triggers on User Login
Add it to the HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Run registry key. The only problem here is it requires write access to the registry, which isn't always available.
Set it up as a windows service. Only do this if you really mean it, and you know for sure you want to run this program for all users on the computer.
This answer is older now. Since I wrote this, Windows 10 was released, which changes how the Start Menu folders work... including the Startup folder. It's not yet clear to me how easy it is to just add or remove a file in that folder without also referencing the internal database Windows uses for these locations.
Here is all way to add your program to startup for Windows Vista, 7, 8, 10
File path
C:\Users\Bureau Briffault\AppData\Roaming\Microsoft\Windows\Start
Menu\Programs\Startup (Visible from task manager, Running on current
user login success, No admin privileges required)
C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start
Menu\Programs\Startup (Visible from task manager, Running on all user
login success, Admin privileges required)
Registry path
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
(Visible from task manager, Running on current user login success, No
admin privileges required)
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
(Not visible from task manager, Running on current user login success,
Running for one login time, No admin privileges required)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
(Visible from task manager, Running on all user login success, Admin
privileges required)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
(Not visible from task manager, Running on all user login success,
Running for one login time, Admin privileges required)
Task scheduler
Microsoft.Win32.Taskscheduler.dll (Not visible from task manager,
Running on windows boot, Running as admin, Admin privileges required)
It`s a so easy solution:
To Add
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("Your Application Name", Application.ExecutablePath);
To Remove
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.DeleteValue("Your Application Name", false);
In addition to Xepher Dotcom's answer, folder path to Windows Startup should be coded that way:
var Startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
/// <summary>
/// Add application to Startup of windows
/// </summary>
/// <param name="appName"></param>
/// <param name="path"></param>
public static void AddStartup(string appName, string path)
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue(appName, "\"" + path + "\"");
}
}
/// <summary>
/// Remove application from Startup of windows
/// </summary>
/// <param name="appName"></param>
public static void RemoveStartup(string appName)
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.DeleteValue(appName, false);
}
}
You can create a registry entry in "HKCU\Software\Microsoft\Windows\CurrentVersion\Run", just be aware that it may work differently on Vista. Your setting might get "virtualized" because of UAC.
If an application is designed to start when Windows starts (as opposed to when a user logs in), your only option is to involve a Windows Service. Either write the application as a service, or write a simple service that exists only to launch the application.
Writing services can be tricky, and can impose restrictions that may be unacceptable for your particular case. One common design pattern is a front-end/back-end pair, with a service that does the work and an application front-end that communicates with the service to display information to the user.
On the other hand, if you just want your application to start on user login, you can use methods 1 or 2 that Joel Coehoorn listed.
if you using wpf, the "ExecutablePath" don't work. So i made a code that work on wpf too.
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue(
"AutoStart.exe",
"\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\""
);
}
I found adding a shortcut to the startup folder to be the easiest way for me. I had to add a reference to "Windows Script Host Object Model" and "Microsoft.CSharp" and then used this code:
IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
string shortcutAddress = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + #"\MyAppName.lnk";
System.Reflection.Assembly curAssembly = System.Reflection.Assembly.GetExecutingAssembly();
IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "My App Name";
shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
shortcut.TargetPath = curAssembly.Location;
shortcut.IconLocation = AppDomain.CurrentDomain.BaseDirectory + #"MyIconName.ico";
shortcut.Save();
You can do this with the win32 class in the Microsoft namespace
using Microsoft.Win32;
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("aldwin", "\"" + Application.ExecutablePath + "\"");
}
Important addition to other's answers using Application.ExecutablePath: if one of the folders containing your exe contains some strange chars (like mine had C# name) then Application.ExecutablePath will return path with different slashes which will result in it not working.
Application.ExecutablePath.Replace('/', '\\') is more appropriate
Add an app to run automatically at startup in Windows 10
Step 1: Select the Windows Start button and scroll to find the app you want to run at startup.
Step 2: Right-click the app, select More, and then select Open file location. This opens the location where the shortcut to the app is saved. If there isn't an option for Open file location, it means the app can't run at startup.
Step 3: With the file location open, press the Windows logo key + R, type shell:startup, then select OK. This opens the Startup folder.
Step 4: Copy and paste or Create the shortcut to the app from the file location to the Startup folder.

Forcing ClickOnce application update on Windows Startup?

I have a ClickOnce application that should automatically check for updates before the application starts. If I start the application manually this also works perfectly.
However I have also added a registry entry to start the application at windows startup and in this case the check for an update is not performed and the application starts just as if there would be no update - I guess because by the time the application starts the connection to the network drive on which the ClickOnce application installation is published is not yet established.
As a workaround I tried to manually force the application in my code by calling this after my MainWindow is already loaded:
private void checkforupdate()
{
try
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
if (ad.CheckForUpdate())
{
MessageBox.Show("Update available!");
ad.Update();
}
}
catch { }
}
However for some reason this code still only triggers an update when I start the application manually, when it's started automatically on Windows start nothing happens.
The part of my code where I call checkforupdate is after there was already a few things loaded from the very same drive where the ClickOnce installation files are published so the connection must be established by then.
Does anyone know what to do?
Ok, I found out that I was having a severe misunderstanding of how the update of a ClickOnce application works: In the registry entry which starts the program at Windows start-up I referred to the .exe file in the mysterious Users\AppData\Local\Apps\2.0.... folders - while this does work of course for starting the application itself it does not have anything to do with the update functionality itself.
The update only happens when referring to ClickOnce Application reference (.appref-ms) Shortcut on the Desktop.

Run C# app on Startup?

I have created a simple weather application and I added the code below to let the user let it run on Startup:
RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (startupCheck.Checked) {
rk.SetValue("WeTile", "\"" + Application.ExecutablePath.ToString() + "\"");
} else {
rk.DeleteValue("WeTile", false);
}
Now this runs fine on both my computers. But when I gave the app to my girlfriend. She said the app does not run on windows start up. I read it online that it could be because of the user permission or the location so I told her to move the app to c:/ and try checking the box again and then restarting. Now it works but on every startup she has the default windows message saying you want to run this app?
How do I get rid of this? What is the best way to add to windows startup that works with both windows 32/64 bit without any user permission disruptions?
It sounds like you may have run afoul of Windows' file blocking security function. Applications created on another computer are automatically blocked from executing unless the user specifically "unblocks" the file. Have your girlfriend right-click on the executable, select "Properties" and see if there is a button at the bottom of the dialog to unblock the file.
Once unblocked, you should no longer see the confirmation prompt at startup.
You could add it to the Windows startup folder, check if it's not there already and if not, add it (assuming this is what the user wants).
See How do I set a program to launch at startup

how can I run an app automatic after restart?

how can I run an app automatic after restart?
(by c# code) I create A new string in 'runOnce' key in registry with the path of the App.
the OS run this APP before it load the OS
my problem is: My APP loads but explorer doesn't load, after I close my APP, explorer loads
I restart the computer in APP, and after restart I want that my APP reopen
When you click restart from your app, make the following modifications to the registry:
Create an entry in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run registry branch.
Use
Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\YourAppName");
to create an entry.
And
RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\YourAppName", true);
myKey.SetValue("YourAppName", "AppExecutablePath", RegistryValueKind.String);
to set the run path.
After the system has restarted, your app starts and removes the restart entry by calling this:
Registry.LocalMachine.DeleteSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\YourAppName");
It seems like your best bet would be to add your program to RunOnce, instead of Run. That way it will be started after the next reboot, but you won't have to worry about erasing the key afterwards.
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
This is a better answer as you should not create a SubKey. Also this will automatically dispose.
string runKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(runKey, true))
{
key.SetValue("MyProgram", #"C:\MyProgram.exe");
}

How do I set a program to launch at startup

I have a small application with a CheckBox option that the user can set if they want the app to start with Windows.
My question is how do I actually set the app to run at startup.
ps: I'm using C# with .NET 2.0.
Thanks to everyone for responding so fast.
Joel, I used your option 2 and added a registry key to the "Run" folder of the current user.
Here's the code I used for anyone else who's interested.
using Microsoft.Win32;
private void SetStartup()
{
RegistryKey rk = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (chkStartUp.Checked)
rk.SetValue(AppName, Application.ExecutablePath);
else
rk.DeleteValue(AppName,false);
}
Several options, in order of preference:
Add it to the current user's Startup folder. This requires the least permissions for your app to run, and gives the user the most control and feedback of what's going on. The down-side is it's a little more difficult determining whether to show the checkbox already checked next time they view that screen in your program.
Add it to the HKey_Current_User\Software\Microsoft\Windows\CurrentVersion\Run registry key. The only problem here is it requires write access to the registry, which isn't always available.
Create a Scheduled Task that triggers on User Login
Add it to the HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Run registry key. The only problem here is it requires write access to the registry, which isn't always available.
Set it up as a windows service. Only do this if you really mean it, and you know for sure you want to run this program for all users on the computer.
This answer is older now. Since I wrote this, Windows 10 was released, which changes how the Start Menu folders work... including the Startup folder. It's not yet clear to me how easy it is to just add or remove a file in that folder without also referencing the internal database Windows uses for these locations.
Here is all way to add your program to startup for Windows Vista, 7, 8, 10
File path
C:\Users\Bureau Briffault\AppData\Roaming\Microsoft\Windows\Start
Menu\Programs\Startup (Visible from task manager, Running on current
user login success, No admin privileges required)
C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start
Menu\Programs\Startup (Visible from task manager, Running on all user
login success, Admin privileges required)
Registry path
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
(Visible from task manager, Running on current user login success, No
admin privileges required)
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
(Not visible from task manager, Running on current user login success,
Running for one login time, No admin privileges required)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
(Visible from task manager, Running on all user login success, Admin
privileges required)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
(Not visible from task manager, Running on all user login success,
Running for one login time, Admin privileges required)
Task scheduler
Microsoft.Win32.Taskscheduler.dll (Not visible from task manager,
Running on windows boot, Running as admin, Admin privileges required)
It`s a so easy solution:
To Add
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("Your Application Name", Application.ExecutablePath);
To Remove
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.DeleteValue("Your Application Name", false);
In addition to Xepher Dotcom's answer, folder path to Windows Startup should be coded that way:
var Startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
/// <summary>
/// Add application to Startup of windows
/// </summary>
/// <param name="appName"></param>
/// <param name="path"></param>
public static void AddStartup(string appName, string path)
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue(appName, "\"" + path + "\"");
}
}
/// <summary>
/// Remove application from Startup of windows
/// </summary>
/// <param name="appName"></param>
public static void RemoveStartup(string appName)
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.DeleteValue(appName, false);
}
}
You can create a registry entry in "HKCU\Software\Microsoft\Windows\CurrentVersion\Run", just be aware that it may work differently on Vista. Your setting might get "virtualized" because of UAC.
If an application is designed to start when Windows starts (as opposed to when a user logs in), your only option is to involve a Windows Service. Either write the application as a service, or write a simple service that exists only to launch the application.
Writing services can be tricky, and can impose restrictions that may be unacceptable for your particular case. One common design pattern is a front-end/back-end pair, with a service that does the work and an application front-end that communicates with the service to display information to the user.
On the other hand, if you just want your application to start on user login, you can use methods 1 or 2 that Joel Coehoorn listed.
if you using wpf, the "ExecutablePath" don't work. So i made a code that work on wpf too.
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue(
"AutoStart.exe",
"\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\""
);
}
I found adding a shortcut to the startup folder to be the easiest way for me. I had to add a reference to "Windows Script Host Object Model" and "Microsoft.CSharp" and then used this code:
IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
string shortcutAddress = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + #"\MyAppName.lnk";
System.Reflection.Assembly curAssembly = System.Reflection.Assembly.GetExecutingAssembly();
IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "My App Name";
shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
shortcut.TargetPath = curAssembly.Location;
shortcut.IconLocation = AppDomain.CurrentDomain.BaseDirectory + #"MyIconName.ico";
shortcut.Save();
You can do this with the win32 class in the Microsoft namespace
using Microsoft.Win32;
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("aldwin", "\"" + Application.ExecutablePath + "\"");
}
Important addition to other's answers using Application.ExecutablePath: if one of the folders containing your exe contains some strange chars (like mine had C# name) then Application.ExecutablePath will return path with different slashes which will result in it not working.
Application.ExecutablePath.Replace('/', '\\') is more appropriate
Add an app to run automatically at startup in Windows 10
Step 1: Select the Windows Start button and scroll to find the app you want to run at startup.
Step 2: Right-click the app, select More, and then select Open file location. This opens the location where the shortcut to the app is saved. If there isn't an option for Open file location, it means the app can't run at startup.
Step 3: With the file location open, press the Windows logo key + R, type shell:startup, then select OK. This opens the Startup folder.
Step 4: Copy and paste or Create the shortcut to the app from the file location to the Startup folder.

Categories