PROWAREtech

articles » current » dot-net » power-status

.NET: Power Status - AC/DC

How to detect the DC/battery operation or AC/plugged-in operation of the computer using C#.

See related: AC/DC Power w/the Windows API (C/C++)

First, check the operating system that the app is running on; if Windows, check the Windows API function GetSystemPowerStatus for ACLineStatus, as in the following example. On Linux/OSX this returns "AC Line Status unknown."

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
	class Program
	{
		public enum ACLineStatus : byte
		{
			Offline = 0, Online = 1, Unknown = 255
		}

		[StructLayout(LayoutKind.Sequential)]
		public class PowerState
		{
			private ACLineStatus ACLineStatus;
			private byte BatteryFlag;
			private byte BatteryLifePercent;
			private byte Reserved1;
			private int BatteryLifeTime;
			private int BatteryFullLifeTime;

			[DllImport("Kernel32", EntryPoint = "GetSystemPowerStatus")]
			private static extern bool GetSystemPowerStatusByRef(PowerState sps);

			private PowerState() { }

			public static ACLineStatus GetPowerLineStatus()
			{
				PowerState state = new PowerState();
				if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && GetSystemPowerStatusByRef(state))
					return state.ACLineStatus;

				return ACLineStatus.Unknown;
			}
		}
		static void Main(string[] args)
		{
			if (PowerState.GetPowerLineStatus() != ACLineStatus.Unknown)
			{
				if(PowerState.GetPowerLineStatus() == ACLineStatus.Offline)
					Console.WriteLine("On Battery");
				else
					Console.WriteLine("On AC Power");
			}
			else
			{
				Console.WriteLine("AC Line Status unknown");
			}
		}
	}
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE