using IWshRuntimeLibrary;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HBLConsole.Service
{
///
/// 系统操作类
///
public class SystemHelper
{
private volatile static SystemHelper _Instance;
public static SystemHelper GetInstance => _Instance ?? (_Instance = new SystemHelper());
private SystemHelper() { }
///
/// 获取当前应用程序名称,包括后缀名
///
public string GetApplicationName => $"{AppDomain.CurrentDomain.FriendlyName}.exe";
///
/// 获取当前应用程序完整路径
///
public string GetApplicationPath => $"{AppDomain.CurrentDomain.BaseDirectory}{GetApplicationName}";
///
/// 创建桌面快捷方式
///
/// 成功或失败
public bool CreateDesktopShortcut()
{
//1、在COM对象中找到 Windows Script Host Object Model
//2、添加引用 using IWshRuntimeLibrary;
string deskTop = string.Empty;
try
{
deskTop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\";
if (System.IO.File.Exists(deskTop + GetApplicationName + ".lnk")) //
{
return true;
//System.IO.File.Delete(deskTop + FileName + ".lnk");//删除原来的桌面快捷键方式
}
WshShell shell = new WshShell();
//快捷键方式创建的位置、名称
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(deskTop + GetApplicationName + ".lnk");
shortcut.TargetPath = GetApplicationPath; //目标文件
//该属性指定应用程序的工作目录,当用户没有指定一个具体的目录时,快捷方式的目标应用程序将使用该属性所指定的目录来装载或保存文件。
shortcut.WorkingDirectory = System.Environment.CurrentDirectory;
shortcut.WindowStyle = 1; //目标应用程序的窗口状态分为普通、最大化、最小化【1,3,7】
shortcut.Description = GetApplicationName; //描述
//shortcut.IconLocation = exePath + "\\logo.ico"; //快捷方式图标
shortcut.Arguments = "";
//shortcut.Hotkey = "CTRL+ALT+F11"; // 快捷键
shortcut.Save(); //必须调用保存快捷才成创建成功
return true;
}
catch (Exception)
{
return false;
}
}
///
/// 设置开机自启动
///
/// true:开机启动,false:不开机自启
public void AutoStart(bool isAuto = true)
{
if (isAuto == true)
{
RegistryKey R_local = Registry.CurrentUser;
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
R_run.SetValue(GetApplicationName, GetApplicationPath);
R_run.Close();
R_local.Close();
}
else
{
RegistryKey R_local = Registry.CurrentUser;
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
R_run.DeleteValue(GetApplicationName, false);
R_run.Close();
R_local.Close();
}
}
///
/// 判断是否是自动启动
///
///
public bool IsAutoStart()
{
//RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\");
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\");
return registryKey.GetValueNames().Contains(GetApplicationName);
}
}
}