using Microsoft.Win32;
using System;
using System.IO;
using System.Windows.Forms;
namespace Apewer.Internals
{
/// 注册表。
static class RegistryHelper
{
/// 用户登录后的启动项。
const string Run = @"Software\Microsoft\Windows\CurrentVersion\Run";
/// HKEY_CURRENT_USER
/// 当前用户的信息。
public static RegistryKey CurrentUser { get => Registry.CurrentUser; }
/// HKEY_LOCAL_MACHINE
/// 系统信息,对所有用户生效,设置需要管理员权限。
public static RegistryKey LocalMachine { get => Registry.LocalMachine; }
/// 获取值。
/// 注册表存储区。
/// 路径。
/// 名称。
/// 值。获取失败时返回 NULL 值。
public static object Get(RegistryKey root, string key, string name)
{
try
{
#if !NET20
using
#endif
var rkey = root.OpenSubKey(key, RegistryKeyPermissionCheck.ReadSubTree);
var names = rkey.GetValueNames();
if (names.Contains(name))
{
var value = rkey.GetValue(name, null);
return value;
}
}
catch { }
return null;
}
/// 获取字符串。
/// 注册表存储区。
/// 路径。
/// 名称。
/// 字符串的值。获取失败时返回 NULL 值。
public static string GetString(RegistryKey root, string key, string name) => Get(root, key, name) as string;
/// 设置字符串,指定 value 为 NULL 可删除该值。
/// 注册表存储区。
/// 路径。
/// 名称。
/// 值。
/// 错误信息。设置成功时返回 NULL 值。
public static string Set(RegistryKey root, string key, string name, string value)
{
try
{
#if !NET20
using
#endif
var rkey = root.OpenSubKey(key, RegistryKeyPermissionCheck.ReadWriteSubTree);
var apps = rkey.GetSubKeyNames();
if (value.IsEmpty()) rkey.DeleteValue(name, true);
else rkey.SetValue(name, value, RegistryValueKind.String);
return null;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// 设置当前用户的启动项。
/// 错误消息。
public static void SetRun(string name, string command)
{
var old = GetString(CurrentUser, Run, name);
if (old.IsEmpty()) Set(CurrentUser, Run, name, command);
}
/// 取消当前用户的启动项。
/// 错误消息。
public static void CancelRun(string name)
{
Set(CurrentUser, Run, name, null);
}
/// 已启用自动启动。
public static bool UserAutoRun
{
get
{
var path = Application.ExecutablePath;
var name = Path.GetFileNameWithoutExtension(path);
var value = GetString(CurrentUser, Run, name);
return value == path;
}
set
{
var path = Application.ExecutablePath;
var name = Path.GetFileNameWithoutExtension(path);
Set(CurrentUser, Run, name, value ? path : null);
}
}
}
}