private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e) { var newStatus = SystemInformation.PowerStatus.PowerLineStatus; if (e.Mode == PowerModes.StatusChange && newStatus != lastStatus) { if (Settings.autoChangePlan) { switch (newStatus) { case PowerLineStatus.Online: DisablePowerSaving(); lastStatus = newStatus; break; case PowerLineStatus.Offline: EnablePowerSaving(); lastStatus = newStatus; break; case PowerLineStatus.Unknown: break; default: throw new ArgumentOutOfRangeException(); } } } }
public void getBatteryStatus() { var prePowerLineStatus = battery.GetPowerStatus(); while (true) { PowerLineStatus.Invoke(new Action(() => { PowerLineStatus.Text = battery.GetPowerLineStatus(); if ((battery.GetPowerStatus() == "Online") && (prePowerLineStatus == "Offline")) { prePowerLineStatus = "Online"; battery.SetDisplayBlackout(battery.GetDefaultScreenTime()); } } )); BatteryLifePercent.Invoke(new Action(() => BatteryLifePercent.Text = (battery.GetBatteryLifePercent() * 100).ToString() + '%')); BatteryLifeRemaining.Invoke(new Action(() => { if (battery.GetBatteryLifeReamaining() != -1) { BatteryLifeRemaining.Text = (battery.GetBatteryLifeReamaining() / 60).ToString() + " min."; } else { BatteryLifeRemaining.Text = "∞"; } } )); } }
/// <summary> /// Module constructor ///Subscribe module on event and depending on the power status select a power plan /// </summary> public PowerLineModule(NotifyIcon notifyIcon) : base(notifyIcon) { SystemEvents.PowerModeChanged += HandleEvent; switch (SystemInformation.PowerStatus.PowerLineStatus) { case PowerLineStatus.Online: DisablePowerSaving(); break; case PowerLineStatus.Offline: EnablePowerSaving(); break; case PowerLineStatus.Unknown: NotifyUser("Unknown Power Line Status", "Power Line Status Changed", ToolTipIcon.Error); break; default: NotifyUser("Unknown Power Line Status", "Power Line Status Changed", ToolTipIcon.Error); break; } _currentPowerLineStatus = SystemInformation.PowerStatus.PowerLineStatus; }
/// <summary> /// Processing events Switching power plan and notifications to users /// </summary> private void HandleEvent(object sender, PowerModeChangedEventArgs e) { if (e.Mode != PowerModes.StatusChange) { return; } switch (SystemInformation.PowerStatus.PowerLineStatus) { case PowerLineStatus.Online: if (_currentPowerLineStatus != PowerLineStatus.Online) { DisablePowerSaving(); NotifyUser("Disable Power Saving", "Power Line Status Changed", ToolTipIcon.None); } break; case PowerLineStatus.Offline: if (_currentPowerLineStatus != PowerLineStatus.Offline) { EnablePowerSaving(); NotifyUser("Enable Power Saving", "Power Line Status Changed", ToolTipIcon.None); } break; default: if (_currentPowerLineStatus != PowerLineStatus.Unknown) { NotifyUser("Unknown Power Line Status", "Power Line Status Changed", ToolTipIcon.Error); } break; } _currentPowerLineStatus = SystemInformation.PowerStatus.PowerLineStatus; }
private void ProcessMessage(string message) { string[] info = message.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); BatteryChargeStatus status = (BatteryChargeStatus)Enum.Parse(typeof(BatteryChargeStatus), info[1]); PowerLineStatus charger = (PowerLineStatus)Enum.Parse(typeof(PowerLineStatus), info[2]); ApplicationStartup.UpdateIcon(int.Parse(info[0]), status, charger); }
internal PowerStatus(BatteryChargeStatus batteryChargeStatus, int batteryFullLifetime, float batteryLifePercent, int batteryLifeRemaining, PowerLineStatus powerLineStatus) { this.battery_charge_status = batteryChargeStatus; this.battery_full_lifetime = batteryFullLifetime; this.battery_life_percent = batteryLifePercent; this.battery_life_remaining = batteryLifeRemaining; this.power_line_status = powerLineStatus; }
public TimeData(DateTime time) { noData = true; this.time = time; charger = PowerLineStatus.Unknown; status = BatteryChargeStatus.Unknown; }
internal PowerStatus (BatteryChargeStatus batteryChargeStatus, int batteryFullLifetime, float batteryLifePercent, int batteryLifeRemaining, PowerLineStatus powerLineStatus) { this.battery_charge_status = batteryChargeStatus; this.battery_full_lifetime = batteryFullLifetime; this.battery_life_percent = batteryLifePercent; this.battery_life_remaining = batteryLifeRemaining; this.power_line_status = powerLineStatus; }
/// <summary> /// Indicates if we're running on battery power. /// If we are, then disable CPU wasting things like animations, background operations, network, I/O, etc /// </summary> public static bool IsRunningOnBattery() { { PowerLineStatus pls = System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus; //Offline means running on battery return(pls == PowerLineStatus.Offline); } }
public TimeData(DateTime date, string line) { string[] data = line.Split(new char[] { ';', '=' }); data[0] = FixNumeric(data[0]); time = date.Add(TimeSpan.Parse(data[0])); percentage = Convert.ToInt32(data[1]); status = (BatteryChargeStatus)Enum.Parse(typeof(BatteryChargeStatus), data[2]); charger = (PowerLineStatus)Enum.Parse(typeof(PowerLineStatus), data[3]); }
/// <inheritdoc /> public void ManagerStart() { _logger.Info($"{nameof(ManagerStart)} was hit"); // write runtime startup metrics var currentVersion = _fm.GetExecutingAssemblyVersion(); var sb = new StringBuilder(); sb.AppendLine($"Starting up {nameof(AlertManager)} (version {currentVersion}) with the following settings:"); sb.AppendLine($"\t{nameof(RuntimeSettings)} is {(_rs == null ? "null" : "initialized")}"); sb.AppendLine($"\t- {nameof(_rs.IsLocalDebugging)} = {_rs.IsLocalDebugging}"); sb.AppendLine($"\t- {nameof(_rs.EmailSmtpServer)} = {_rs.EmailSmtpServer}"); sb.AppendLine($"\t- {nameof(_rs.EmailSmtpPort)} = {_rs.EmailSmtpPort}"); sb.AppendLine($"\t- {nameof(_rs.EmailSmtpUseSsl)} = {_rs.EmailSmtpUseSsl}"); sb.AppendLine($"\t- {nameof(_rs.EmailSenderAddress)} = {_rs.EmailSenderAddress}"); sb.AppendLine($"\t- {nameof(_rs.EmailRecipientAddress)} = {_rs.EmailRecipientAddress}"); _logger.Info(sb.ToString()); // initialize uptime tracker _uptimeDelayInMinutes = _rs.IsLocalDebugging ? 1 : 20; _uptimeTimer = new System.Threading.Timer(LogUptime); _uptimeTimer.Change(0, (int)TimeSpan.FromMinutes(_uptimeDelayInMinutes).TotalMilliseconds); // report battery presence _isBatteryDetected = IsBatteryAvailable(); if (_isBatteryDetected) { _logger.Info("Battery was found"); } else { _logger.Warn("No battery was found, so changes in power state will not be reported"); } // report power draw _powerSource = SystemInformation.PowerStatus.PowerLineStatus; if (_powerSource == PowerLineStatus.Online) { _logger.Info($"{nameof(PowerLineStatus)} - Running on wall power"); } else if (_powerSource == PowerLineStatus.Offline) { _logger.Warn($"{nameof(PowerLineStatus)} - Running on battery"); } else { _logger.Error($"{nameof(PowerLineStatus)} - Unable to determine power draw source!"); } // if on battery power mode, then drop into notification logic if (_powerSource == PowerLineStatus.Offline) { NotifyPowerOnBattery(); } }
/// <summary> /// This method gets information about the battery using WMI /// </summary> public void UpdateData() { _percent = SystemInformation.PowerStatus.BatteryLifePercent * 100; _connectionType = SystemInformation.PowerStatus.PowerLineStatus; var seacher = new ManagementObjectSearcher("SELECT * FROM Win32_Battery").Get(); foreach (var property in seacher) { _remainingTime = (UInt32)property["EstimatedRunTime"]; } }
private void updateWindow(object sender, EventArgs e) /// auto update gui on every timer call { // hide taskbar icon if minimized (keep notify icon) if (this.WindowState == FormWindowState.Minimized) { Hide(); /// hide taskbar icon if window is minimized } // battery percent (batChargePercent & batChargeLabel) float batPercent = SystemInformation.PowerStatus.BatteryLifePercent * 100; /// battery percent gets returned as decimal of 1 batChargePercent.Text = ((int)batPercent).ToString() + '%'; batChargeBar.Value = (int)batPercent; /// assign batPercent value to progress bar // log full charge if ((int)batPercent >= 90) { System.IO.File.WriteAllText("log.txt", DateTime.Now.ToString()); /// write current time to file if charge >90% } // compare full charge to now DateTime fullCharge = Convert.ToDateTime(System.IO.File.ReadAllText("log.txt")); /// get time of last full charge TimeSpan sinceCharge = DateTime.Now.Subtract(fullCharge); /// compare to current time for "time since last charge" // charging status (batChargingStatusInfo) PowerLineStatus chargingStatus = SystemInformation.PowerStatus.PowerLineStatus; /// get powerline status if (chargingStatus.ToString() == "Online") /// if else statement is only useful to change the string that gets displayed { string batChargingState = "Charging"; // set gui text batChargingStatusInfo.Text = batChargingState; // set notify icon text batInfoIcon.Text = "Charge: " + ((int)batPercent).ToString() + "%\n" + "Status: " + batChargingState + "\n" + "Last charge: " + TimeUtil.ToHumanTimeString(sinceCharge); } else { // same as before string batChargingState = "Discharging"; batChargingStatusInfo.Text = batChargingState; batInfoIcon.Text = "Charge: " + ((int)batPercent).ToString() + "%\n" + "Status: " + batChargingState + "\n" + "Last charge: " + TimeUtil.ToHumanTimeString(sinceCharge); } timeSinceLastFullInfo.Text = TimeUtil.ToHumanTimeString(sinceCharge); /// put time since last charge on screen ///// to-do: /// run on startup and in notification area only }
public Service1() { InitializeComponent(); _CurrStatus = SystemInformation.PowerStatus.PowerLineStatus; EventLogger = new System.Diagnostics.EventLog(); if (!System.Diagnostics.EventLog.SourceExists(ServiceName)) { System.Diagnostics.EventLog.CreateEventSource(ServiceName, EventLogger.Log); } EventLogger.Source = ServiceName; }
/// <summary> /// <para>Returns the current Power status</para> /// </summary> /// <returns></returns> public static TreeNode GetStatus() { TreeNode tnMain = new TreeNode("Power"); tnMain.Nodes.Add("Active power scheme: " + ActivePowerScheme.Name + " (" + ActivePowerScheme.Guid.ToString() + ")"); tnMain.Nodes.Add("Power Line Status: " + PowerLineStatus.ToString()); tnMain.Nodes.Add("Battery charge status: " + BatteryChargeStatus.ToString()); tnMain.Nodes.Add("Battery available: " + BatteryAvailable.ToString()); tnMain.Nodes.Add("Battery full life time: " + BatteryFullLifetime.ToString()); tnMain.Nodes.Add("Battery remaining life time: " + BatteryLifeRemaining.ToString()); tnMain.Nodes.Add("Battery charge percent: " + BatteryLifePercent + "%"); return(tnMain); }
private void CheckPowerLineStatus() { //checks if power has been lost or restored PowerLineStatus currPowerLineStatus = SystemInformation.PowerStatus.PowerLineStatus; if (prevPowerLineStatus == PowerLineStatus.Online) { if (currPowerLineStatus == PowerLineStatus.Offline || currPowerLineStatus == PowerLineStatus.Unknown) { if (!pNotif) { pNotif = true; switch (cbShutdownAction.SelectedIndex) { case 0: int action = SelectionInputDialog.ShowSelectionInputDialog(this, "Choose Shutdown Action", ShutdownManager.GetShutdownActions(SHUTDOWN_TYPE.SHUTDOWN_POWER_LOSS)); //make sure we have a valid shutdown action if (action >= 0) { ShutdownManager.Shutdown((SHUTDOWN_ACTION_POWER_LOSS)action); } break; default: SHUTDOWN_ACTION_POWER_LOSS sdAction = (SHUTDOWN_ACTION_POWER_LOSS)cbShutdownAction.SelectedIndex; ShutdownManager.Shutdown(sdAction); //MessageBox.Show(this, "Computer Shutdown Mode: " + sdAction.ToString(), "Warning"); break; } //notifications come as dialogs which will block the //execution of the statements after it //execution continues when the dialog is closed, //when this happens, notification is closed pNotif = false; } } } else { if (currPowerLineStatus == PowerLineStatus.Online) { if (pNotif) { SelectionInputDialog.CloseDialog(); pNotif = false; } } } prevPowerLineStatus = currPowerLineStatus; }
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) { if (powerStatus == PowerBroadcastStatus.PowerStatusChange) { if (SystemInformation.PowerStatus.BatteryChargeStatus != BatteryChargeStatus.NoSystemBattery && SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online && _CurrStatus != PowerLineStatus.Online) { _Player.PlayAudio(); } // update current status _CurrStatus = SystemInformation.PowerStatus.PowerLineStatus; } return(true); }
public static int GetLevel(PowerLineStatus powerStatus, int currentLevel) { Load(); if (LevelPerPowerStatus.TryGetValue(powerStatus, out var level)) { return(level); } else { LevelPerPowerStatus.Add(powerStatus, currentLevel); Save(); Debug.WriteLine($"[Storage] Read: {powerStatus} {level}% (default)"); return(currentLevel); } }
public void OnBatteryInfoUpdate(object sender, System.Timers.ElapsedEventArgs args) { lastPercentage = percentage; lastStatus = status; lastCharger = charger; percentage = (int)(SystemInformation.PowerStatus.BatteryLifePercent * 100); status = SystemInformation.PowerStatus.BatteryChargeStatus; charger = SystemInformation.PowerStatus.PowerLineStatus; if (client != null && (percentage != lastPercentage || status != lastStatus || charger != lastCharger)) { client.SendToClient(percentage + ";" + status + ";" + charger); } }
private void Power_Manager_Load(object sender, EventArgs e) { isHideConfirmed = false; //setup the battery status background monitor batteryStatusMonitor.WorkerReportsProgress = true; batteryStatusMonitor.WorkerSupportsCancellation = false; batteryStatusMonitor.RunWorkerAsync(); cbShutdownAction.Items.AddRange(ShutdownManager.GetShutdownActions(SHUTDOWN_TYPE.SHUTDOWN_POWER_LOSS)); cbAutoShutdownAction.Items.AddRange(ShutdownManager.GetShutdownActions(SHUTDOWN_TYPE.SHUTDOWN_NORMAL)); cbShutdownAction.SelectedIndex = 0; cbAutoShutdownAction.SelectedIndex = 0; prevPowerLineStatus = SystemInformation.PowerStatus.PowerLineStatus; }
private void HandlePowerModeChanged(object sender, PowerModeChangedEventArgs e) { Debug.WriteLine($"{nameof(HandlePowerModeChanged)} triggered: {e.Mode}"); PowerBroadcastStatus powerBroadcastStatus = new PowerBroadcastStatus(); Debug.WriteLine($"{nameof(powerBroadcastStatus)} = {powerBroadcastStatus}"); PowerLineStatus powerLineStatus = SystemInformation.PowerStatus.PowerLineStatus; Debug.WriteLine($"{nameof(powerLineStatus)} = {powerLineStatus} --- Is Running Battery? {(powerLineStatus == PowerLineStatus.Offline)}"); switch (e.Mode) { case PowerModes.Resume: // online state resumed break; case PowerModes.StatusChange: // status changed from AC to battery or vice-versa Debug.WriteLine($"{nameof(HandlePowerModeChanged)} received {e.Mode} -- current {nameof(PowerBroadcastStatus)} is {powerBroadcastStatus}"); switch (powerLineStatus) { case PowerLineStatus.Online: _alertManager.NotifyPowerFromWall(); break; case PowerLineStatus.Offline: _alertManager.NotifyPowerOnBattery(); break; case PowerLineStatus.Unknown: Debug.WriteLine($"Unable to process value '{powerBroadcastStatus}'. Exiting early."); break; default: throw new NotSupportedException($"Unsure how to handle status of '{powerLineStatus}' !!"); } break; case PowerModes.Suspend: // going into suspended power mode break; } _currentPowerMode = e.Mode; _currentPowerLineStatus = powerLineStatus; }
void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e) { if (e.Mode == Microsoft.Win32.PowerModes.StatusChange) { PowerStatus powerStatus = SystemInformation.PowerStatus; /*string str = "lastPowerLineStatus: " + lastPowerLineStatus + "\n" * "\n" + * "powerStatus:\n" + * "powerStatus.PowerLineStatus: " + powerStatus.PowerLineStatus + "\n" + * "powerStatus.BatteryLifeRemaining: " + powerStatus.BatteryLifeRemaining + "\n" + * "powerStatus.BatteryLifePercent: " + powerStatus.BatteryLifePercent + "\n" + * "powerStatus.BatteryFullLifetime: " + powerStatus.BatteryFullLifetime + "\n" + * "powerStatus.BatteryChargeStatus: " + powerStatus.BatteryChargeStatus + "\n"; * MessageBox.Show(str);*/ if (powerStatus.PowerLineStatus == PowerLineStatus.Offline && lastPowerLineStatus == PowerLineStatus.Online && powerStatus.BatteryLifePercent >= 0.95) { // Unplugged power event, battery almost fully charged, reset Usage and Total counters usageSeconds = 0; totalSeconds = 0; hasBeenPluggedIn = false; } if (powerStatus.PowerLineStatus == PowerLineStatus.Online && lastPowerLineStatus == PowerLineStatus.Offline) { // Plugged-in power event hasBeenPluggedIn = true; UpdateLabelTime(); } lastPowerLineStatus = powerStatus.PowerLineStatus; } else if (e.Mode == Microsoft.Win32.PowerModes.Suspend) { // TODO: Distinguish between Hibernate and Sleep, and not increase the totalSeconds counter after a Hibernate event sleptAt = DateTime.Now; } else if (e.Mode == Microsoft.Win32.PowerModes.Resume) { // TODO: Distinguish between Hibernate and Sleep, and not increase the totalSeconds counter after a Hibernate event DateTime wokeUpAt = DateTime.Now; totalSeconds += (long)(wokeUpAt - sleptAt).TotalSeconds; } }
public static void SetLevel(PowerLineStatus powerStatus, int newLevel) { Load(); if (LevelPerPowerStatus.TryGetValue(powerStatus, out var storedLevel)) { if (storedLevel != newLevel) { LevelPerPowerStatus[powerStatus] = newLevel; Debug.WriteLine($"[Storage] Write: {powerStatus} {newLevel}%"); Save(); } } else { LevelPerPowerStatus.Add(powerStatus, newLevel); Debug.WriteLine($"[Storage] Write: {powerStatus} {newLevel}% (new)"); Save(); } }
/// <summary> /// Checks the power line status, and turns the idle blocker on or off if necessary. /// </summary> private void checkPowerLineStatus() { PowerLineStatus powerLineStatus = SystemInformation.PowerStatus.PowerLineStatus; if (powerLineStatus == PowerLineStatus.Online) // on power { if (!blocker.Active && Properties.Settings.Default.EnableOnPower) { SetProgramState(true); } } else if (powerLineStatus == PowerLineStatus.Offline) // on battery { if (blocker.Active && Properties.Settings.Default.DisableOnBattery) { SetProgramState(false); } } }
private void GetInformation() { DateTime last = DateTime.Now.Subtract(new TimeSpan(0, 2, 0)); while (!stopThread) { if (last.AddMinutes(1) <= DateTime.Now) { percentage = SystemInformation.PowerStatus.BatteryLifePercent; timeLeft = SystemInformation.PowerStatus.BatteryLifeRemaining; status = SystemInformation.PowerStatus.BatteryChargeStatus; charger = SystemInformation.PowerStatus.PowerLineStatus; last = DateTime.Now; } Thread.Sleep(50); } }
private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e) { var newStatus = SystemInformation.PowerStatus.PowerLineStatus; if (e.Mode == PowerModes.StatusChange && newStatus != lastStatus) { trayIcon.BalloonTipTitle = Resources.Form1_OnPowerModeChanged_Power_status_has_changed; switch (newStatus) { case PowerLineStatus.Online: DisablePowerSaving(); trayIcon.BalloonTipIcon = ToolTipIcon.None; trayIcon.BalloonTipText = Resources.Form1_OnPowerModeChanged_Power_saving_is_disabled; lastStatus = newStatus; break; case PowerLineStatus.Offline: EnablePowerSaving(); trayIcon.BalloonTipIcon = ToolTipIcon.None; trayIcon.BalloonTipText = Resources.Form1_OnPowerModeChanged_Power_saving_is_enabled; lastStatus = newStatus; break; case PowerLineStatus.Unknown: trayIcon.BalloonTipIcon = ToolTipIcon.Error; trayIcon.BalloonTipText = Resources.Form1_OnPowerModeChanged_Problem_occured_determining_power_mode; break; default: throw new ArgumentOutOfRangeException(); } trayIcon.Visible = true; trayIcon.ShowBalloonTip(1000); trayIcon.Visible = false; } }
public PowerSupply.Source GetSource() { try { PowerLineStatus status = System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus; if (status == PowerLineStatus.Online) { return(PowerSupply.Source.AC); } if (status == PowerLineStatus.Offline) { return(PowerSupply.Source.Battery); } return(PowerSupply.Source.Unknown); } catch { return(PowerSupply.Source.Unknown); } }
private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e) { var newStatus = SystemInformation.PowerStatus.PowerLineStatus; if (e.Mode == PowerModes.StatusChange && newStatus != lastStatus) { switch (newStatus) { case PowerLineStatus.Online: if (f != null) { f.Close(); } Console.WriteLine("Питание есть"); lastStatus = newStatus; break; case PowerLineStatus.Offline: Console.WriteLine("Питание кончилось"); f = new TimerDialog(); f.Show(); // lastStatus = newStatus; break; case PowerLineStatus.Unknown: break; default: throw new ArgumentOutOfRangeException(); } } }
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online && lastStatus == PowerLineStatus.Online) //OK: no notification { return; } if (SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online && lastStatus != PowerLineStatus.Online) //UPS back online again { WriteToLog("UPS is back online.", EventLogEntryType.Information, 13371); } if (SystemInformation.PowerStatus.PowerLineStatus != PowerLineStatus.Online && lastStatus != PowerLineStatus.Online && lastEventSent.AddMinutes(Settings.Default.time_reminder_min) < DateTime.Now) //UPS offline for a longer time { WriteToLog("UPS is still offline.", EventLogEntryType.Error, 13372); } if (SystemInformation.PowerStatus.PowerLineStatus != PowerLineStatus.Online && lastStatus == PowerLineStatus.Online) //UPS just went offline { WriteToLog("UPS went from online to offline.", EventLogEntryType.Error, 13373); timeGoingOffline = DateTime.Now; } if (SystemInformation.PowerStatus.PowerLineStatus != PowerLineStatus.Online && timeGoingOffline.AddMinutes(Settings.Default.time_to_wait_before_shutdown_eventlog_entry_min) < DateTime.Now) { WriteToLog("UPS is still offline (" + Settings.Default.time_to_wait_before_shutdown_eventlog_entry_min + " min). You should shut down your system.", EventLogEntryType.Error, 13380); } lastStatus = SystemInformation.PowerStatus.PowerLineStatus; } catch (Exception ex) { WriteToLog("Exception in Timer: \r\n" + ex.Message, EventLogEntryType.Error, 13377); } }
private MenuItem GeneratePowerData() { string pluggedStatus, powerDescription; MenuItem powerDataMenuItem = new MenuItem(); powerDataMenuItem.Enabled = false; float batteryPercentage = SystemInformation.PowerStatus.BatteryLifePercent; BatteryChargeStatus batteryStatus = SystemInformation.PowerStatus.BatteryChargeStatus; if (batteryStatus == BatteryChargeStatus.NoSystemBattery) { powerDescription = "No battery detected"; powerDataMenuItem.Text = powerDescription; return(powerDataMenuItem); } PowerLineStatus powerLineStatus = SystemInformation.PowerStatus.PowerLineStatus; pluggedStatus = SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Online ? "Plugged in" : "Unplugged"; // Discharging, time to battery die if (powerLineStatus == PowerLineStatus.Offline) { powerDescription = GenerateBatteryOfflineData(batteryPercentage); } else { int secondsToFullCharge = SystemInformation.PowerStatus.BatteryFullLifetime; powerDescription = $"{batteryPercentage * 100}% - {pluggedStatus}"; } powerDataMenuItem.Text = powerDescription; return(powerDataMenuItem); }
public void loop() { while (true) { PowerLineStatus pls = SystemInformation.PowerStatus.PowerLineStatus; if (pls.ToString() == "Online" && wallpaperEngineStatus == false) { //turn on service wallpaperEngineService.Start(); wallpaperEngineStatus = true; } else if (pls.ToString() == "Offline" && wallpaperEngineStatus == true) { //turn off service and main process processes = Process.GetProcesses().ToList(); //Reload processes wallpaperEngineService.Stop(); processes.Where(x => x.ProcessName == "wallpaper64").FirstOrDefault()?.Kill(); wallpaperEngineStatus = false; } Thread.Sleep(interval); } }
private void BatterPlugCheck() { if(this.actualLineStatus != _power.PowerLineStatus) { this.actualLineStatus = _power.PowerLineStatus; if (_power.PowerLineStatus == PowerLineStatus.Online) { if (PowerSchemeHelper.GetPowerActiveScheme() != _maxPlan) { Thread.Sleep(1000); try { LogoForm logo = new LogoForm(500, 1500, 20, global::PowerPlanChanger.Properties.Resources.PerformanceBattery); SetPlan(_maxPlan); } catch { } } } else if (_power.PowerLineStatus == PowerLineStatus.Offline) { if (PowerSchemeHelper.GetPowerActiveScheme() != _ecoPlan) { Thread.Sleep(1000); try { LogoForm logo = new LogoForm(500, 1500, 20, global::PowerPlanChanger.Properties.Resources.EnergySaver); SetPlan(_ecoPlan); } catch { } } } } }
public Main() { InitializeComponent(); LoadCreditials(); if (Properties.Settings.Default.mode == "standard") { mode = Mode.Standard; } else if (Properties.Settings.Default.mode == "expert") { mode = Mode.Expert; } mutex = new Mutex(true, Application.ProductName, out is_single_instance); //Create Mutex if (!is_single_instance) //If second instance of application is running { this.Close(); //Close current application return; } this.Hide(); //Hide window cpu = new PerformanceCounter(); //Create CPU usage counter object ram = new PerformanceCounter(); //Create RAM usage counter object harddisk_read = new PerformanceCounter(); //Create harddisk read usage counter object harddisk_write = new PerformanceCounter(); //Create harddisk write usage couter object network_interface = new PerformanceCounterCategory("Network Interface"); //Create network interface network_instances = network_interface.GetInstanceNames(); //Get all instances from network interface network_download = new PerformanceCounter[network_instances.Length]; //Get number of all network instances (download) server_uptime = new PerformanceCounter(); for (int instance = 0; instance < network_download.Length; instance++) //For all network instances (download) { network_download[instance] = new PerformanceCounter(); //Add network instance (download) to an array } network_upload = new PerformanceCounter[network_instances.Length]; //Get number of all network instances (upload) for (int instance = 0; instance < network_upload.Length; instance++) //For all network instances (upload) { network_upload[instance] = new PerformanceCounter(); //Add network instance (upload) to an array } harddisk_read.CategoryName = "PhysicalDisk"; //Get Harddisk counter category harddisk_read.CounterName = "Disk Read Bytes/sec"; //Get Harddisk counter name harddisk_read.InstanceName = "_Total"; //Get Harddisk counter instance name if (login_showed == false) //If login dialog was not showed { //If values in registry is null or values are default if (server_petname == null || contact_email == null || secret_key == null || server_petname == "server_petname" || contact_email == "*****@*****.**" || secret_key == "secret_key") { Form login = new Settings(); //Create form Login login.ShowDialog(); //Show login } login_showed = true; //Set Login dialog was showed } if(login_showed==true) { timerSender.Start(); //Start timer update } hostname = Dns.GetHostName(); ip_host_entry = Dns.GetHostEntry(hostname); ip_addresses = ip_host_entry.AddressList; startToolStripMenuItemStartStop.Text = "Stop"; startToolStripMenuItemStartStop.Image = Properties.Resources.stop; sending = Sending.Run; updater = Process.GetProcessesByName("Cloudiff updater"); if (updater.Length != 0) { foreach (Process process in updater) { process.Kill(); } } if (Environment.Is64BitOperatingSystem) { operation_system_32_64bit = "64bit"; } else { operation_system_32_64bit = "32bit"; } cpu_cores = Environment.ProcessorCount; RegistryKey cpu_32_64bit_key = Registry.LocalMachine.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"); if (cpu_32_64bit_key.GetValue("Identifier").ToString().IndexOf("64") > 0) { cpu_32_64bit = "64bit"; } else { cpu_32_64bit = "32bit"; } cpu_architecture = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); power = SystemInformation.PowerStatus; power_line_status = power.PowerLineStatus; }
//Form Loading public void APP_Refresh() { this.RefreshButtonsBitmap(); this.SetPosition(); if (this._plugCheck || this._changePointOn) { this.actualLineStatus = PowerLineStatus.Unknown; _timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); _timer.Interval = 2000; _timer.Enabled = true; } }
void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e) { if (e.Mode == Microsoft.Win32.PowerModes.StatusChange) { PowerStatus powerStatus = SystemInformation.PowerStatus; /*string str = "lastPowerLineStatus: " + lastPowerLineStatus + "\n" "\n" + "powerStatus:\n" + "powerStatus.PowerLineStatus: " + powerStatus.PowerLineStatus + "\n" + "powerStatus.BatteryLifeRemaining: " + powerStatus.BatteryLifeRemaining + "\n" + "powerStatus.BatteryLifePercent: " + powerStatus.BatteryLifePercent + "\n" + "powerStatus.BatteryFullLifetime: " + powerStatus.BatteryFullLifetime + "\n" + "powerStatus.BatteryChargeStatus: " + powerStatus.BatteryChargeStatus + "\n"; MessageBox.Show(str);*/ if (powerStatus.PowerLineStatus == PowerLineStatus.Offline && lastPowerLineStatus == PowerLineStatus.Online && powerStatus.BatteryLifePercent >= 0.95) { // Unplugged power event, battery almost fully charged, reset Usage and Total counters usageSeconds = 0; totalSeconds = 0; hasBeenPluggedIn = false; } if (powerStatus.PowerLineStatus == PowerLineStatus.Online && lastPowerLineStatus == PowerLineStatus.Offline) { // Plugged-in power event hasBeenPluggedIn = true; UpdateLabelTime(); } lastPowerLineStatus = powerStatus.PowerLineStatus; } else if (e.Mode == Microsoft.Win32.PowerModes.Suspend) { // TODO: Distinguish between Hibernate and Sleep, and not increase the totalSeconds counter after a Hibernate event sleptAt = DateTime.Now; } else if (e.Mode == Microsoft.Win32.PowerModes.Resume) { // TODO: Distinguish between Hibernate and Sleep, and not increase the totalSeconds counter after a Hibernate event DateTime wokeUpAt = DateTime.Now; totalSeconds += (long)(wokeUpAt - sleptAt).TotalSeconds; } }