2016-04-23 42 views
0

我已经创建了一个程序,我将它作为发布版本构建到exe中。当你双击exe文件时,程序应该将自己添加到启动中,所以每次启动pc时,程序都会运行。尽管没有错误,但它并没有将其添加到启动中。该计划也按预期运行。将程序添加到启动

这是处理程序添加到启动代码:

public static void AddApplicationToStartup() 
{ 
    using(RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) 
    { 
     key.SetValue("WindowsProcesses", "\"" + Application.ExecutablePath + "\""); 
    } 

} 

...这个代码是主要的“纲要”类里面写。

+1

你在'key.SetValue'上的错误检查在哪里? WindowsProcesses存在吗?如果是这样,你的价值是否增加了? (原来,你的错误在OpenSubKey上检查?) –

+2

不要这样做。这对于一个程序来说是不好的行为。 –

+0

这是一篇很好的CodePlex文章,介绍如何从C#中完成此任务。文章看起来很直截了当,但基本上使用Windows DLL来创建快捷方式。 http://www.codeproject.com/Articles/146757/Add-Remove-Startup-Folder-Shortcut-to-Your-App –

回答

0

添加应用程序的路径这样

public static void AddApplicationToStartup() 
     { 

      using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) 
      { 
       key.SetValue("WindowsProcesses", Application.ExecutablePath.ToString()); 
      } 

     } 
+0

ok编辑正确,谢谢 – Mostafiz

+0

第三行缺少一个括号在结束,但这段代码给了我错误不能从'Microsoft.Win32.RegistryKey'转换为'字符串' –

+0

@OliverDungey我已更新我的代码,希望这一次将工作并不会抛出任何异常 – Mostafiz

-1

我用这对我的程序和它完美对我很好。它采用可执行文件并在启动注册表所在的系统注册表中添加对其的引用。在这种情况下,我的可执行文件被命名为“Lemon Soda.exe”。

string fileName = @"\Lemon Soda.exe"; 
string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); 

RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); 
registryKey.SetValue("Lemon Soda", targetPath + fileName); 
registryKey.Close(); 
+0

给了我没有错误,但没有解决这个问题。 –