ソースを参照

修改注册表工具类

yuzhengyang 8 年 前
コミット
59665567ba

+ 31 - 1
Fork.Net/Y.Utils/AppUtils/StartupTool.cs

@@ -3,10 +3,40 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
+using Y.Utils.WindowsUtils.InfoUtils;
 
 namespace Y.Utils.AppUtils
 {
-    class StartupTool
+    public class StartupTool
     {
+        public static string RegeditRunKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
+        public static bool Regedit(string appName, string appFile, bool start = true)
+        {
+            if (start)
+            {
+                //添加启动注册表
+                if (RegisterTool.Write(RegeditRunKey, appName, appFile))
+                    return true;
+            }
+            else
+            {
+                //删除启动注册表
+                if (RegisterTool.Delete(RegeditRunKey, appName))
+                    return true;
+            }
+            return false;
+        }
+        public static bool Shortcut(string appName, string appFile, bool start = true)
+        {
+            if (start)
+            {
+                //添加开机启动开始菜单项
+            }
+            else
+            {
+                //删除开机启动开始菜单项
+            }
+            return false;
+        }
     }
 }

+ 133 - 12
Fork.Net/Y.Utils/WindowsUtils/InfoUtils/RegisterTool.cs

@@ -5,12 +5,7 @@ namespace Y.Utils.WindowsUtils.InfoUtils
 {
     public class RegisterTool
     {
-        /// <summary>
-        /// 写入注册表项
-        /// </summary>
-        /// <param name="key">SOFTWARE\\NC_VideoConferenceSystem</param>
-        /// <param name="name">RegTime</param>
-        /// <param name="value">yyyy-MM-dd hh:mm:ss</param>
+        [Obsolete]
         public static bool Write(string key, string name, string value)
         {
             try
@@ -26,12 +21,7 @@ namespace Y.Utils.WindowsUtils.InfoUtils
                 return false;
             }
         }
-        /// <summary>
-        /// 读取注册表项
-        /// </summary>
-        /// <param name="key">SOFTWARE\\NC_VideoConferenceSystem</param>
-        /// <param name="name">Path</param>
-        /// <returns></returns>
+        [Obsolete]
         public static string Read(string key, string name)
         {
             try
@@ -45,6 +35,7 @@ namespace Y.Utils.WindowsUtils.InfoUtils
             catch (Exception e) { }
             return null;
         }
+        [Obsolete]
         public static bool Delete(string key, string name)
         {
             try
@@ -59,5 +50,135 @@ namespace Y.Utils.WindowsUtils.InfoUtils
                 return false;
             }
         }
+
+        /// <summary>
+        /// 添加注册表值
+        /// </summary>
+        /// <param name="key"></param>
+        /// <param name="name"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        public static bool SetValue(string key, string name, string value)
+        {
+            try
+            {
+                using (RegistryKey RKey = Create(key))
+                {
+                    RKey.SetValue(name, value);
+                }
+                return true;
+            }
+            catch (Exception e)
+            {
+                return false;
+            }
+        }
+        /// <summary>
+        /// 删除注册表值
+        /// </summary>
+        /// <param name="key"></param>
+        /// <param name="name"></param>
+        /// <returns></returns>
+        public static string GetValue(string key, string name)
+        {
+            try
+            {
+                using (RegistryKey RKey = Open(key, false))
+                {
+                    if (RKey != null)
+                    {
+                        return RKey.GetValue(name) != null ? RKey.GetValue(name).ToString() : "";
+                    }
+                }
+            }
+            catch (Exception e) { }
+            return null;
+        }
+        /// <summary>
+        /// 删除注册表值
+        /// </summary>
+        /// <param name="key"></param>
+        /// <param name="name"></param>
+        /// <returns></returns>
+        public static bool DeleteValue(string key, string name)
+        {
+            try
+            {
+                using (RegistryKey RKey = Open(key, true))
+                {
+                    if (RKey != null)
+                        RKey.DeleteValue(name);
+                }
+                return true;
+            }
+            catch (Exception e)
+            {
+                return false;
+            }
+        }
+        /// <summary>
+        /// 分离注册表根目录和子目录
+        /// </summary>
+        /// <param name="key"></param>
+        /// <param name="reg"></param>
+        /// <param name="sub"></param>
+        /// <returns></returns>
+        private static bool ExtractInfo(string key, out string reg, out string sub)
+        {
+            reg = ""; sub = "";
+            int splitPos = 1;
+            if ((splitPos = key.IndexOf('\\')) > 0)
+            {
+                reg = key.Substring(0, splitPos);
+                sub = key.Substring(splitPos + 1);
+                return true;
+            }
+            return false;
+        }
+        /// <summary>
+        /// 打开注册表相应目录
+        /// </summary>
+        /// <param name="key">目标子项</param>
+        /// <param name="writable">是否具有写权限</param>
+        /// <returns></returns>
+        private static RegistryKey Open(string key, bool writable)
+        {
+            string regkey, subkey;
+            if (ExtractInfo(key, out regkey, out subkey))
+            {
+                switch (regkey)
+                {
+                    case "HKEY_CLASSES_ROOT": return Registry.ClassesRoot.OpenSubKey(subkey, writable);
+                    case "HKEY_CURRENT_USER": return Registry.CurrentUser.OpenSubKey(subkey, writable);
+                    case "HKEY_LOCAL_MACHINE": return Registry.LocalMachine.OpenSubKey(subkey, writable);
+                    case "HKEY_USERS": return Registry.Users.OpenSubKey(subkey, writable);
+                    case "HKEY_CURRENT_CONFIG": return Registry.CurrentConfig.OpenSubKey(subkey, writable);
+                    default: return Registry.CurrentUser.OpenSubKey(subkey, writable);
+                }
+            }
+            return Registry.CurrentUser.OpenSubKey(subkey, writable);
+        }
+        /// <summary>
+        /// 创建或打开注册表相应目录
+        /// </summary>
+        /// <param name="key">目标子项</param>
+        /// <returns></returns>
+        private static RegistryKey Create(string key)
+        {
+            string regkey, subkey;
+            if (ExtractInfo(key, out regkey, out subkey))
+            {
+                switch (regkey)
+                {
+                    case "HKEY_CLASSES_ROOT": return Registry.ClassesRoot.CreateSubKey(subkey);
+                    case "HKEY_CURRENT_USER": return Registry.CurrentUser.CreateSubKey(subkey);
+                    case "HKEY_LOCAL_MACHINE": return Registry.LocalMachine.CreateSubKey(subkey);
+                    case "HKEY_USERS": return Registry.Users.CreateSubKey(subkey);
+                    case "HKEY_CURRENT_CONFIG": return Registry.CurrentConfig.CreateSubKey(subkey);
+                    default: return Registry.CurrentUser.CreateSubKey(subkey);
+                }
+            }
+            return Registry.CurrentUser.CreateSubKey(subkey);
+        }
     }
 }

+ 39 - 12
Fork.Net/Y.Utils/WindowsUtils/InfoUtils/ShortcutTool.cs

@@ -4,20 +4,47 @@ namespace Y.Utils.WindowsUtils.InfoUtils
 {
     public class ShortcutTool
     {
-        public static void Create(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
+        public static bool Create(string directory, string shortcutName, string targetPath,
+            string description = null, string iconLocation = null)
         {
-            DirTool.Create(directory);
+            try
+            {
+                if (!Directory.Exists(directory))
+                {
+                    Directory.CreateDirectory(directory);
+                }
 
-            //添加引用 Com 中搜索 Windows Script Host Object Model
-            string shortcutPath = System.IO.Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
-            IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
-            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象
-            shortcut.TargetPath = targetPath;//指定目标路径
-            shortcut.WorkingDirectory = System.IO.Path.GetDirectoryName(targetPath);//设置起始位置
-            shortcut.WindowStyle = 1;//设置运行方式,默认为常规窗口
-            shortcut.Description = description;//设置备注
-            shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
-            shortcut.Save();//保存快捷方式
+                //添加引用 Com 中搜索 Windows Script Host Object Model
+                string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
+                IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
+                IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象
+                shortcut.TargetPath = targetPath;//指定目标路径
+                shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
+                shortcut.WindowStyle = 1;//设置运行方式,默认为常规窗口
+                shortcut.Description = description;//设置备注
+                shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
+                shortcut.Save();//保存快捷方式
+
+                return true;
+            }
+            catch
+            { }
+            return false;
+        }
+
+        public static bool Delete(string directory, string shortcutName)
+        {
+            try
+            {
+                string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
+                if (File.Exists(shortcutPath))
+                {
+                    File.Delete(shortcutPath);
+                }
+                return true;
+            }
+            catch { }
+            return false;
         }
     }
 }

+ 143 - 0
Fork.Net/Y.Utils/WindowsUtils/InfoUtils/TaskSchedulerTool.cs

@@ -0,0 +1,143 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Y.Utils.WindowsUtils.InfoUtils
+{
+    public class TaskSchedulerTool
+    {
+        ///// <summary>
+        ///// get all tasks
+        ///// </summary>
+        //public static IRegisteredTaskCollection GetAllTasks()
+        //{
+        //    TaskSchedulerClass ts = new TaskSchedulerClass();
+        //    ts.Connect(null, null, null, null);
+        //    ITaskFolder folder = ts.GetFolder("\\");
+        //    IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);
+        //    return tasks_exists;
+        //}
+        ///// <summary>
+        ///// create task
+        ///// </summary>
+        ///// <param name="creator"></param>
+        ///// <param name="taskName"></param>
+        ///// <param name="path"></param>
+        ///// <param name="interval"></param>
+        ///// <returns>state</returns>
+        //public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string path, string interval)
+        //{
+        //    try
+        //    {
+        //        Delete(taskName);
+
+        //        //new scheduler
+        //        TaskSchedulerClass scheduler = new TaskSchedulerClass();
+        //        //pc-name/ip,username,domain,password
+        //        scheduler.Connect(null, null, null, null);
+        //        //get scheduler folder
+        //        ITaskFolder folder = scheduler.GetFolder("\\");
+
+
+        //        //set base attr 
+        //        ITaskDefinition task = scheduler.NewTask(0);
+        //        task.RegistrationInfo.Author = "McodsAdmin";//creator
+        //        task.RegistrationInfo.Description = "...";//description
+
+        //        //set trigger  (IDailyTrigger ITimeTrigger)
+        //        ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
+        //        tt.Repetition.Interval = interval;// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器
+        //        tt.StartBoundary = "2015-04-09T14:27:25";//start time
+
+        //        //set action
+        //        IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
+        //        action.Path = path;
+
+        //        task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时
+        //        task.Settings.DisallowStartIfOnBatteries = false;//只有在交流电源下才执行
+        //        task.Settings.RunOnlyIfIdle = false;//仅当计算机空闲下才执行
+
+        //        IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task,
+        //                                                            (int)_TASK_CREATION.TASK_CREATE, null, //user
+        //                                                            null, // password
+        //                                                            _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
+        //                                                            "");
+        //        IRunningTask runTask = regTask.Run(null);
+        //        return runTask.State;
+
+        //    }
+        //    catch (Exception ex)
+        //    {
+        //        throw ex;
+        //    }
+
+        //}
+
+        //public static _TASK_STATE Create(string name, string file, string author, string desc)
+        //{
+        //    try
+        //    {
+        //        //删除重名任务
+        //        Delete(name);
+        //        //new scheduler
+        //        TaskSchedulerClass scheduler = new TaskSchedulerClass();
+        //        //pc-name/ip,username,domain,password
+        //        scheduler.Connect(null, null, null, null);
+        //        //get scheduler folder
+        //        ITaskFolder folder = scheduler.GetFolder("\\");
+        //        //set base attr 
+        //        ITaskDefinition task = scheduler.NewTask(0);
+        //        task.RegistrationInfo.Author = author;//创建者
+        //        task.RegistrationInfo.Description = desc;//描述
+        //                                                 //set trigger  (IDailyTrigger ITimeTrigger)
+        //        task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);
+        //        //set action
+        //        IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
+        //        action.Path = file;
+        //        task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时
+        //        task.Settings.DisallowStartIfOnBatteries = false;//只有在交流电源下才执行
+        //        task.Settings.RunOnlyIfIdle = false;//仅当计算机空闲下才执行
+
+        //        IRegisteredTask regTask =
+        //            folder.RegisterTaskDefinition(name, task,
+        //            (int)_TASK_CREATION.TASK_CREATE, null, //user
+        //            null, // password
+        //            _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
+        //            "");
+        //        IRunningTask runTask = regTask.Run(null);
+        //        return runTask.State;
+        //    }
+        //    catch (Exception ex)
+        //    {
+        //        throw ex;
+        //    }
+        //}
+        //public static void Delete(string name)
+        //{
+        //    if (Exists(name))
+        //    {
+        //        TaskSchedulerClass ts = new TaskSchedulerClass();
+        //        ts.Connect(null, null, null, null);
+        //        ITaskFolder folder = ts.GetFolder("\\");
+        //        folder.DeleteTask(name, 0);
+        //    }
+        //}
+        //public static bool Exists(string name)
+        //{
+        //    var isExists = false;
+        //    IRegisteredTaskCollection tasks_exists = GetAllTasks();
+        //    for (int i = 1; i <= tasks_exists.Count; i++)
+        //    {
+        //        IRegisteredTask t = tasks_exists[i];
+        //        if (t.Name.Equals(name))
+        //        {
+        //            isExists = true;
+        //            break;
+        //        }
+        //    }
+        //    return isExists;
+        //}
+    }
+}

+ 1 - 0
Fork.Net/Y.Utils/Y.Utils.csproj

@@ -108,6 +108,7 @@
     <Compile Include="DataUtils\DateTimeUtils\UnixTimeTool.cs" />
     <Compile Include="WindowsUtils\InfoUtils\ScreenCapture.cs" />
     <Compile Include="WindowsUtils\InfoUtils\ShortcutTool.cs" />
+    <Compile Include="WindowsUtils\InfoUtils\TaskSchedulerTool.cs" />
   </ItemGroup>
   <ItemGroup>
     <None Include="packages.config" />