Run application on startup in Windows 8 C#

风流意气都作罢 提交于 2019-12-06 12:50:00

问题


This code:

RegistryKey rKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

            rKey.DeleteValue(Application.ProductName, false);
            rKey.SetValue(Application.ProductName, Application.ExecutablePath, RegistryValueKind.String);

doesn't work on Windows 8. I don't have idea why because on Windows 7 and on Windows XP this solution works.

Can you help me?


回答1:


In order to set something in the registry you need to run the application as an administrator. To do so you first add a Application Manifest File to the Properties "folder" in the project.

Then you change

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

To:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Then I don't know if the way you get the current executable path is correct, for me this have worked at least:

class Program
{
    private static void RegisterAsRun()
    {
        string exePath = new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath;           
        Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", "TestApp", exePath, RegistryValueKind.String);
    }


    static void Main(string[] args)
    {
        RegisterAsRun();

        Console.WriteLine("Hello!");
        Console.ReadLine();
    }
}

Another note is that if the application is compiled in x86 and the OS is x64 the registry key will end up in the Wow64 registry which makes it the following path:

HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run



来源:https://stackoverflow.com/questions/22487631/run-application-on-startup-in-windows-8-c-sharp

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