how can I run an app automatic after restart?

心已入冬 提交于 2019-11-30 05:17:59

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");
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!