반응형
public class StartUpHelper
{
	private string programName;
	private string exeFilePath;
	private const string AutoRunRegistryKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

	public StartUpHelper(string programName , string exeFilePath)
	{
		this.programName = programName;
		this.exeFilePath = string.Format($"\"{exeFilePath}\"");
	}

	public bool IsReregistered()
	{
		bool isReregistered = false;
		RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(AutoRunRegistryKeyPath, true);

		try
		{
			if (registryKey.GetValue(programName) == null) return false;

			string value = (string)registryKey.GetValue(programName);

			isReregistered = value == exeFilePath;
		}
		catch (Exception)
		{
			isReregistered = false;
		}
		finally
		{
			registryKey.Close();
		}

		return isReregistered;
	}

	public void RegisterStartUp()
	{
		RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(AutoRunRegistryKeyPath, true);

		registryKey.SetValue(programName, exeFilePath);
		registryKey.Close();
	}

	public void UnRegisterStartUp()
	{
		if (!IsReregistered()) return;

		RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(AutoRunRegistryKeyPath, true);

		registryKey.DeleteValue(programName, false);
		registryKey.Close();
	}
}
반응형

+ Recent posts