How to Detect the DC/Battery Operation or AC Operation in .NET using C#

See related: .NET examples & 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");
			}
		}
	}
}

Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site.
OK