mirror of
https://github.com/ckaczor/ChrisKaczor.Wpf.Application.StartWithWindows.git
synced 2026-01-14 01:25:39 -05:00
38 lines
1.4 KiB
C#
38 lines
1.4 KiB
C#
using System;
|
|
using System.Reflection;
|
|
using Microsoft.Win32;
|
|
|
|
namespace ChrisKaczor.Wpf.Application
|
|
{
|
|
public static class ApplicationExtensions
|
|
{
|
|
public static void SetStartWithWindows(this System.Windows.Application application, bool value)
|
|
{
|
|
var applicationName = Assembly.GetEntryAssembly()!.GetName().Name;
|
|
|
|
SetStartWithWindows(application, applicationName!, value);
|
|
}
|
|
|
|
public static void SetStartWithWindows(this System.Windows.Application application, string applicationName, bool value)
|
|
{
|
|
var applicationPath = $"\"{Assembly.GetEntryAssembly()!.Location}\"";
|
|
|
|
SetStartWithWindows(application, applicationName, applicationPath, value);
|
|
}
|
|
|
|
public static void SetStartWithWindows(this System.Windows.Application _, string applicationName, string applicationPath, bool value)
|
|
{
|
|
// Open the run registry key
|
|
var registryKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true) ?? throw new ApplicationException("Unable to open registry key");
|
|
|
|
// Delete any existing key
|
|
registryKey.DeleteValue(applicationName, false);
|
|
|
|
// If auto start should not be on then we're done
|
|
if (!value) return;
|
|
|
|
// Set the registry key
|
|
registryKey.SetValue(applicationName, applicationPath);
|
|
}
|
|
}
|
|
} |