我不得不在工作中做类似的项目。下面的代码或多或少是我写的。我不能保证它是万无一失的,但它似乎与我测试的注册管理机构一起工作。
public static class ProcessHelper
{
const string RegistrySubKeyName =
@"Software\Microsoft\Windows\CurrentVersion\Run";
public static void LaunchStartupPrograms()
{
foreach (string commandLine in GetStartupProgramCommandLines())
{
string fileName;
string arguments;
if (File.Exists(commandLine))
{
fileName = commandLine;
arguments = String.Empty;
}
else if (commandLine.StartsWith("\""))
{
int secondQuoteIndex = commandLine.IndexOf("\"", 1);
fileName = commandLine.Substring(1, secondQuoteIndex - 1);
if (commandLine.EndsWith("\""))
{
arguments = String.Empty;
}
else
{
arguments = commandLine.Substring(secondQuoteIndex + 2);
}
}
else
{
int firstSpaceIndex = commandLine.IndexOf(' ');
if (firstSpaceIndex == -1)
{
fileName = commandLine;
arguments = String.Empty;
}
else
{
fileName = commandLine.Substring(0, firstSpaceIndex);
arguments = commandLine.Substring(firstSpaceIndex + 1);
}
}
Process.Start(fileName, arguments);
}
}
static IEnumerable<string> GetStartupProgramCommandLines()
{
using (RegistryKey key =
Registry.CurrentUser.OpenSubKey(RegistrySubKeyName))
{
foreach (string name in key.GetValueNames())
{
string commandLine = (string) key.GetValue(name);
yield return commandLine;
}
}
using (RegistryKey key =
Registry.LocalMachine.OpenSubKey(RegistrySubKeyName))
{
foreach (string name in key.GetValueNames())
{
string commandLine = (string) key.GetValue(name);
yield return commandLine;
}
}
}
}
哦,我的上帝,这看起来很惊人。目前并不需要万无一失。我将通过它来看看它是如何适合我的代码库的。你摇滚! – Giallo 2015-04-01 16:01:11