Run C# app on Startup? - c#

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

Related

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.

How to spawn a process that DOES NOT request admin rights on the machine in c#

I seem to be asking the opposite of everyone else. I want to spawn a process and NOT have it request admin rights on the machine.
I have 2 executables:
1) Application
2) Updater
The application periodically checks a web service to see if there are any software updates. If there are, it will spawn the updater .exe and close the current application.
The updater then downloads the files, unpacks and spawns the original process.
Nothing here seems to need admin rights, and yet UAC keeps getting involved.
This is an application that runs on a machine with no keyboard or mouse and I want the update process to run with no user interaction.
Do I have to turn off UAC in order to get this to work, or have I got something enabled that I need to disable?
I think the only other piece to add here is that I'm using ClickOnce to deploy a minimal app initially that will always run the updater and download the latest copy of the program.
I'm using the following lines to spawn the updater or the calling app:
if (System.IO.File.Exists("AppUpdater.exe"))
{
Process.Start(fileName: "AppUpdater.exe", arguments: appId + " " + versionNo + " " + callingApp);
}
if (File.Exists(CallingApp))
{
Process.Start(CallingApp);
}
Thanks
Turns out it was my executable for the updater application that was causing the issue. I had to change some settings in the project properties.
I'm not sure exactly which one was causing the issue because I changed a number of settings to match another application that didn't cause the UAC message to be displayed.
I suspect the main one was the "Icon and Manifest" setting; I changed this to "Embed manifest with default settings".

Process.Start won't work

I am trying to launch a process from a web page's back-end code/app pool. This process will launch an App that i built myself.
For some reason, the process only works / runs when i start it from VS2013... it never works when i launch it from IIS(7.5) itself.
I am on a Windows 7 machine (both IIS host, and App location), and I've setup my web site to only be accessible via internal network.
Here's the code, followed by the config / attempts to fix the issue:
protected void btn_DoIt_Click(object sender, EventArgs e)
{
string file_text = this.txt_Urls.Text;
if (!String.IsNullOrWhiteSpace(file_text))
File.WriteAllText(ConfigurationManager.AppSettings["filePath"], file_text);
ProcessStartInfo inf = new ProcessStartInfo();
SecureString ss = GetSecureString("SomePassword");
inf.FileName = #"........\bin\Release\SomeExecutable.exe";
inf.Arguments = ConfigurationManager.AppSettings["filePath"];
inf.UserName = "SomeUserName";
inf.Password = ss;
inf.UseShellExecute = false;
//launch desktop app, but don't close it in case we want to see the results!
try
{
Process.Start(inf);
}
catch(Exception ex)
{
this.txt_Urls.Text = ex.Message;
}
this.txt_Urls.Enabled = false;
this.btn_DoIt.Enabled = false;
this.txt_Urls.Text = "Entries received and process started. Check local machine for status update, or use refresh below.";
}
Here are the things I've tried to resolve the issue:
Made sure the executing assembly was built with AnyCPU instead of
x86
Ensured that the AppPool that runs the app, also runs under the same account (SomeUsername) as the ProcessStartInfo specified.
Ensured that the specific user account has full access to the executable's folder.
Ensured that IIS_USR has full access to the executable's folder.
Restarted both the app pool and IIS itself many times over implementing these fixes
I am now at a loss as to why this simply will not launch the app... when i first looked into the event log, i saw that the app would die immediately with code 1000:KERNELBASE.dll, which got me on the AnyCPU config instead of X86 fix... that fixed the event log entries but the app still doesn't start (nothing comes up in task manager), and i get no errors in the event log...
if someone could help me fix this problem i would really appreciate it. This would allow me to perform specific tasks on my main computer from any device on my network (phone, tablet, laptop, etc etc) without having to be in front of my main PC...
UPDATE
The comment to my OP, and ultimate answer from #Bradley Uffner actually nailed the problem on the head: My "app" is actually a desktop application with a UI, and in order to run that application, IIS would need to be able to get access to the desktop and the UI, just like if it were a person sitting down in front of the PC. This of course is not the case since IIS is running only as a service account and it makes sense that it shouldn't be launching UI programs in the background. Also see his answer for one way of getting around this.
Your best bet might be to try writing this as 2 parts. A web site that posts commands to a text file (or database, or some other persistent storage), and a desktop application that periodically polls that file (database, etc) for changes and executes those commands. You could write out the entire command line, including exe path command arguments, and switches.
This is the only way I can really think of to allow a service application like IIS to execute applications that require a desktop context with a logged in user.
You should assign a technical user with enough high priviliges to the running application pool. By default the application pool is running with ApplicationPoolIdentity identy which has a very low priviliges.

How to autostart a c sharp application when booting windows?

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");

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");
}

Categories