GUI/StartupManager.cs
author moel.mich
Sun, 08 Aug 2010 13:57:26 +0000
changeset 165 813d8bc3192f
parent 139 9611b4d9d898
child 185 edb59f3745e8
permissions -rw-r--r--
Refactored the hardware monitoring code into a library (Issue 101).
     1 /*
     2   
     3   Version: MPL 1.1/GPL 2.0/LGPL 2.1
     4 
     5   The contents of this file are subject to the Mozilla Public License Version
     6   1.1 (the "License"); you may not use this file except in compliance with
     7   the License. You may obtain a copy of the License at
     8  
     9   http://www.mozilla.org/MPL/
    10 
    11   Software distributed under the License is distributed on an "AS IS" basis,
    12   WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
    13   for the specific language governing rights and limitations under the License.
    14 
    15   The Original Code is the Open Hardware Monitor code.
    16 
    17   The Initial Developer of the Original Code is 
    18   Michael Möller <m.moeller@gmx.ch>.
    19   Portions created by the Initial Developer are Copyright (C) 2009-2010
    20   the Initial Developer. All Rights Reserved.
    21 
    22   Contributor(s):
    23 
    24   Alternatively, the contents of this file may be used under the terms of
    25   either the GNU General Public License Version 2 or later (the "GPL"), or
    26   the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
    27   in which case the provisions of the GPL or the LGPL are applicable instead
    28   of those above. If you wish to allow use of your version of this file only
    29   under the terms of either the GPL or the LGPL, and not to allow others to
    30   use your version of this file under the terms of the MPL, indicate your
    31   decision by deleting the provisions above and replace them with the notice
    32   and other provisions required by the GPL or the LGPL. If you do not delete
    33   the provisions above, a recipient may use your version of this file under
    34   the terms of any one of the MPL, the GPL or the LGPL.
    35  
    36 */
    37 
    38 using System;
    39 using System.Collections.Generic;
    40 using System.IO;
    41 using System.Runtime.InteropServices;
    42 using System.Security;
    43 using System.Security.Principal;
    44 using System.Windows.Forms;
    45 using Microsoft.Win32;
    46 using OpenHardwareMonitor.TaskScheduler;
    47 
    48 namespace OpenHardwareMonitor.GUI {
    49   public class StartupManager {
    50 
    51     private TaskSchedulerClass scheduler;
    52     private bool startup;
    53     private bool isAvailable;
    54 
    55     private const string REGISTRY_RUN =
    56       @"Software\Microsoft\Windows\CurrentVersion\Run";
    57 
    58     private bool IsAdministrator() {
    59       try {
    60         WindowsIdentity identity = WindowsIdentity.GetCurrent();
    61         WindowsPrincipal principal = new WindowsPrincipal(identity);
    62         return principal.IsInRole(WindowsBuiltInRole.Administrator);
    63       } catch {
    64         return false;
    65       }
    66     }
    67 
    68     public StartupManager() {
    69       int p = (int)System.Environment.OSVersion.Platform;
    70       if ((p == 4) || (p == 128)) {
    71         scheduler = null;        
    72         isAvailable = false;
    73         return;
    74       }
    75 
    76       if (IsAdministrator()) {
    77         try {
    78           scheduler = new TaskSchedulerClass();
    79           scheduler.Connect(null, null, null, null);
    80         } catch {
    81           scheduler = null;
    82         }
    83 
    84         if (scheduler != null) {
    85           try {
    86             // check if the taskscheduler is running
    87             IRunningTaskCollection collection = scheduler.GetRunningTasks(0);            
    88 
    89             ITaskFolder folder = scheduler.GetFolder("\\Open Hardware Monitor");
    90             IRegisteredTask task = folder.GetTask("Startup");
    91             startup = (task != null) && 
    92               (task.Definition.Triggers.Count > 0) &&
    93               (task.Definition.Triggers[1].Type == 
    94                 TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON) &&
    95               (task.Definition.Actions.Count > 0) &&
    96               (task.Definition.Actions[1].Type ==
    97                 TASK_ACTION_TYPE.TASK_ACTION_EXEC) &&
    98               (task.Definition.Actions[1] as IExecAction != null) &&
    99               ((task.Definition.Actions[1] as IExecAction).Path ==
   100                 Application.ExecutablePath);
   101               
   102           } catch (IOException) {
   103             startup = false;
   104           } catch (UnauthorizedAccessException) {
   105             scheduler = null;
   106           } catch (COMException) {
   107             scheduler = null;
   108           }
   109         } 
   110       } else {
   111         scheduler = null;
   112       }
   113 
   114       if (scheduler == null) {
   115         try {
   116           using (RegistryKey key =
   117             Registry.CurrentUser.OpenSubKey(REGISTRY_RUN)) {
   118             startup = false;
   119             if (key != null) {
   120               string value = (string)key.GetValue("OpenHardwareMonitor");
   121               if (value != null)
   122                 startup = value == Application.ExecutablePath;
   123             }            
   124           }
   125           isAvailable = true;
   126         } catch (SecurityException) {
   127           isAvailable = false;
   128         }
   129       } else {
   130         isAvailable = true;
   131       }
   132     }
   133 
   134     private void CreateSchedulerTask() {
   135       ITaskDefinition definition = scheduler.NewTask(0);
   136       definition.RegistrationInfo.Description =
   137         "This task starts the Open Hardware Monitor on Windows startup.";
   138       definition.Principal.RunLevel =
   139         TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;
   140       definition.Settings.DisallowStartIfOnBatteries = false;
   141       definition.Settings.StopIfGoingOnBatteries = false;
   142       definition.Settings.ExecutionTimeLimit = "PT0S";
   143 
   144       ILogonTrigger trigger = (ILogonTrigger)definition.Triggers.Create(
   145         TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);
   146 
   147       IExecAction action = (IExecAction)definition.Actions.Create(
   148         TASK_ACTION_TYPE.TASK_ACTION_EXEC);
   149       action.Path = Application.ExecutablePath;
   150       action.WorkingDirectory =
   151         Path.GetDirectoryName(Application.ExecutablePath);
   152 
   153       ITaskFolder root = scheduler.GetFolder("\\");
   154       ITaskFolder folder;
   155       try {
   156         folder = root.GetFolder("Open Hardware Monitor");
   157       } catch (IOException) {
   158         folder = root.CreateFolder("Open Hardware Monitor", "");
   159       }
   160       folder.RegisterTaskDefinition("Startup", definition,
   161         (int)TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null,
   162         TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");
   163     }
   164 
   165     private void DeleteSchedulerTask() {
   166       ITaskFolder root = scheduler.GetFolder("\\");
   167       try {
   168         ITaskFolder folder = root.GetFolder("Open Hardware Monitor");
   169         folder.DeleteTask("Startup", 0);
   170       } catch (IOException) { }
   171       try {
   172         root.DeleteFolder("Open Hardware Monitor", 0);
   173       } catch (IOException) { }
   174     }
   175 
   176     private void CreateRegistryRun() {
   177       RegistryKey key = Registry.CurrentUser.CreateSubKey(REGISTRY_RUN);
   178       key.SetValue("OpenHardwareMonitor", Application.ExecutablePath);
   179     }
   180 
   181     private void DeleteRegistryRun() {
   182       RegistryKey key = Registry.CurrentUser.CreateSubKey(REGISTRY_RUN);
   183       key.DeleteValue("OpenHardwareMonitor");
   184     }
   185 
   186     public bool IsAvailable {
   187       get { return isAvailable; }
   188     }
   189 
   190     public bool Startup {
   191       get {
   192         return startup;
   193       }
   194       set {
   195         if (startup != value) {
   196           startup = value;
   197           if (isAvailable) {
   198             if (scheduler != null) {
   199               if (startup)
   200                 CreateSchedulerTask();
   201               else
   202                 DeleteSchedulerTask();
   203             } else {
   204               if (startup)
   205                 CreateRegistryRun();
   206               else
   207                 DeleteRegistryRun();
   208             }
   209           }
   210         }
   211       }
   212     }
   213   }
   214 
   215 }