473,326 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

DeviceIOControl for Battery Information

Hi All,

Is there a way to call and get "Battery Information" using "DeviceIOControl" API.

Appreciated, if answer with some utility or sample code.

Thanks,
Sanjay
Nov 23 '12 #1
4 6525
PsychoCoder
465 Expert Mod 256MB
Unfortunately Bytes.com isn't a code writing service, we're a forum of like-minded people offering help to those who are willing to help themselves.

Show us the code you've tried along with any issues or error messages you're getting and we'll do our best to help :)
Nov 23 '12 #2
Sure... Below is the code:

Expand|Select|Wrap|Line Numbers
  1.   #region Variables Declaration
  2.  
  3.         private const int DIGCF_DEFAULT = 0x00000001;  // only valid with DIGCF_DEVICEINTERFACE
  4.         private const int DIGCF_PRESENT = 0x00000002;
  5.         private const int DIGCF_ALLCLASSES = 0x00000004;
  6.         private const int DIGCF_PROFILE = 0x00000008;
  7.         private const int DIGCF_DEVICEINTERFACE = 0x00000010;
  8.  
  9.         const int GENERIC_READ = 80000000;
  10.         const uint GENERIC_WRITE = 0x40000000;
  11.         internal static uint OPEN_EXISTING = 3;
  12.         internal static uint FILE_ATTRIBUTE_NORMAL = 0x80;
  13.         internal static uint FILE_SHARE_READ = 1;
  14.         internal static uint FILE_SHARE_WRITE = 2;
  15.  
  16.         public const uint METHOD_BUFFERED = 0;
  17.         public const uint FILE_ANY_ACCESS = 0x0001;
  18.         public const uint FILE_DEVICE_BATTERY = 0x294044; //0x294040; //0x00000029;
  19.  
  20.         public static readonly Guid GUID_DEVCLASS_BATTERY = new Guid(0x72631e54, 0x78a4, 0x11d0, 0xbc, 0xf7, 0x00, 0xaa, 0x00, 0xb7, 0xb3, 0x2a);
  21.         #endregion
  22.  
  23.         #region Windows APIs
  24.  
  25.         [DllImport("setupapi.dll", CharSet = CharSet.Auto)]
  26.         static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, [MarshalAs(UnmanagedType.LPTStr)] string Enumerator,
  27.                                                        IntPtr hwndParent, uint Flags);
  28.         [DllImport("setupapi.dll")]
  29.         internal static extern Int32 SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, Int32 MemberIndex, ref  SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);
  30.  
  31.         [DllImport("setupapi.dll", SetLastError = true)]
  32.         protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, out uint nRequiredSize, IntPtr lpDeviceInfoData);
  33.  
  34.         [DllImport("setupapi.dll", SetLastError = true)]
  35.         protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA oDetailData, uint nDeviceInterfaceDetailDataSize, out uint nRequiredSize, IntPtr lpDeviceInfoData);
  36.  
  37.         [DllImport("kernel32.dll", SetLastError = true)]
  38.         public static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)] string lpFileName, uint dwDesiredAccess,
  39.             uint dwShareMode, IntPtr SecurityAttributes,
  40.             uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
  41.  
  42.         [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  43.         public static extern SafeFileHandle CreateFile(string fileName, [MarshalAs(UnmanagedType.U4)] FileAccess fileAccess,
  44.              [MarshalAs(UnmanagedType.U4)] FileShare fileShare, IntPtr securityAttributes,
  45.              [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition, [MarshalAs(UnmanagedType.U4)] EFileAttributes flags,
  46.               IntPtr template);
  47.  
  48.         [DllImport("wimgapi.dll", EntryPoint = "WIMCloseHandle", SetLastError = true)]
  49.         public static extern int WIMCloseHandle(IntPtr hObject);
  50.  
  51.         [DllImport(@"hid.dll", CharSet = CharSet.Auto, SetLastError = true)]
  52.         public static extern void HidD_GetHidGuid(out Guid gHid);
  53.  
  54.         [DllImport("setupapi.dll")]
  55.         internal static extern Int32 SetupDiClassNameFromGuid(ref Guid ClassGuid, StringBuilder className, Int32 ClassNameSize, ref Int32 RequiredSize);
  56.  
  57.         [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  58.         public static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr hDevInfo, IntPtr devInvo,
  59.             ref Guid interfaceClassGuid, Int32 memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
  60.  
  61.         [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  62.         public static extern UInt16 SetupDiDestroyDeviceInfoList(IntPtr hDevInfo);
  63.  
  64.         //[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
  65.         //public static extern bool DeviceIoControl(SafeHandle hDevice, uint dwIoControlCode,
  66.         //    IntPtr lpInBuffer, uint nInBufferSize, IntPtr lpOutBuffer, uint nOutBufferSize, out int lpBytesReturned,
  67.         //    IntPtr lpOverlapped);
  68.  
  69.         //[DllImport("Kernel32.dll", SetLastError = false, CharSet = CharSet.Auto)]
  70.         //public static extern bool DeviceIoControl(SafeFileHandle hDevice, uint IoControlCode,
  71.         //    [MarshalAs(UnmanagedType.AsAny)][In] BATTERY_QUERY_INFORMATION InBuffer, uint nInBufferSize,
  72.         //[MarshalAs(UnmanagedType.AsAny)][Out] BATTERY_INFORMATION OutBuffer, out uint nOutBufferSize, ref uint pBytesReturned,
  73.         //[In] IntPtr lpOverlapped);
  74.  
  75.         [DllImport("Kernel32.dll", SetLastError = false, CharSet = CharSet.Auto)]
  76.         public static extern bool DeviceIoControl(SafeFileHandle hDevice, uint IoControlCode,
  77.             ref BATTERY_QUERY_INFORMATION InBuffer, uint nInBufferSize,
  78.         ref BATTERY_INFORMATION OutBuffer, uint nOutBufferSize, ref uint pBytesReturned,
  79.         IntPtr lpOverlapped);
  80.  
  81.         [DllImport("Kernel32.dll", SetLastError = false, CharSet = CharSet.Auto)]
  82.         public static extern bool DeviceIoControl(SafeFileHandle hDevice, uint IoControlCode, ref ulong InBuffer,
  83.              uint nInBufferSize, ref ulong OutBuffer, uint nOutBufferSize, ref ulong pBytesReturned, object lpOverlapped);
  84.  
  85.         [DllImport("kernel32.dll")]
  86.         public static extern int DeviceIoControl(IntPtr hDevice, int dwIoControlCode, ref short lpInBuffer, int nInBufferSize,
  87.             IntPtr lpOutBuffer, int nOutBufferSize, ref int lpBytesReturned, IntPtr lpOverlapped);
  88.  
  89.         #endregion
  90.  
  91.         #region Structures and Enums
  92.  
  93.         [StructLayout(LayoutKind.Sequential, Pack = 1)]
  94.         public struct SP_DEVICE_INTERFACE_DATA
  95.         {
  96.             public UInt32 cbSize;
  97.             public Guid InterfaceClassGuid;
  98.             public UInt32 Flags;
  99.             public UIntPtr Reserved;
  100.         }
  101.         [StructLayout(LayoutKind.Sequential, Pack = 1)]
  102.         public struct SP_DEVICE_INTERFACE_DETAIL_DATA
  103.         {
  104.             public UInt32 cbSize;
  105.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
  106.             public string DevicePath;
  107.         }
  108.  
  109.         [StructLayout(LayoutKind.Sequential, Pack = 1)]
  110.         public struct BATTERY_QUERY_INFORMATION
  111.         {
  112.             public ulong BatteryTag;
  113.             public BATTERY_QUERY_INFORMATION_LEVEL InformationLevel;
  114.             public long AtRate;
  115.         }
  116.  
  117.         [StructLayout(LayoutKind.Sequential, Pack = 1)]
  118.         public struct BATTERY_QUERY_INFORMATION_LEVEL
  119.         {
  120.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
  121.             public string BatteryDeviceName;
  122.             public ulong BatteryEstimatedTime;
  123.             public BATTERY_REPORTING_SCALE BatteryGranularityInformation;
  124.             public BATTERY_INFORMATION BatteryInformation;
  125.             public BATTERY_MANUFACTURE_DATE BatteryManufactureDate;
  126.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
  127.             public string BatteryManufactureName;
  128.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
  129.             public string BatterySerialNumber;
  130.             public ulong BatteryTemperature;
  131.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
  132.             public string BatteryUniqueID;
  133.         }
  134.  
  135.         [StructLayout(LayoutKind.Sequential, Pack = 1)]
  136.         public struct BATTERY_REPORTING_SCALE
  137.         {
  138.             public ulong Granularity;
  139.             public ulong Capacity;
  140.         }
  141.  
  142.         [StructLayout(LayoutKind.Sequential, Pack = 1)]
  143.         public struct BATTERY_MANUFACTURE_DATE
  144.         {
  145.             public char Day;
  146.             public char Month;
  147.             public ushort Year;
  148.         }
  149.  
  150.         [StructLayout(LayoutKind.Sequential, Pack = 1)]
  151.         public struct BATTERY_INFORMATION
  152.         {
  153.             public ulong Capabilities;
  154.             public char Technology;
  155.             public char[] Reserved;
  156.             public char[] Chemistry;
  157.             public ulong DesignCapacity;
  158.             public ulong FullChargeCapacity;
  159.             public ulong DefaultAlert1;
  160.             public ulong DefaultAlert2;
  161.             public ulong CriticalBias;
  162.             public ulong CycleCount;
  163.         }
  164.  
  165.         [Flags]
  166.         public enum EFileAttributes : uint
  167.         {
  168.             Readonly = 0x00000001,
  169.             Hidden = 0x00000002,
  170.             System = 0x00000004,
  171.             Directory = 0x00000010,
  172.             Archive = 0x00000020,
  173.             Device = 0x00000040,
  174.             Normal = 0x00000080,
  175.             Temporary = 0x00000100,
  176.             SparseFile = 0x00000200,
  177.             ReparsePoint = 0x00000400,
  178.             Compressed = 0x00000800,
  179.             Offline = 0x00001000,
  180.             NotContentIndexed = 0x00002000,
  181.             Encrypted = 0x00004000,
  182.             Write_Through = 0x80000000,
  183.             Overlapped = 0x40000000,
  184.             NoBuffering = 0x20000000,
  185.             RandomAccess = 0x10000000,
  186.             SequentialScan = 0x08000000,
  187.             DeleteOnClose = 0x04000000,
  188.             BackupSemantics = 0x02000000,
  189.             PosixSemantics = 0x01000000,
  190.             OpenReparsePoint = 0x00200000,
  191.             OpenNoRecall = 0x00100000,
  192.             FirstPipeInstance = 0x00080000
  193.         }
  194.  
  195.         #endregion
  196.  
  197.  #region Methods
  198.         public void ConnectWithDevice()
  199.         {
  200.             int index = 0;
  201.             Guid guid = GUID_DEVCLASS_BATTERY;
  202.  
  203.             // get the GUID of the HID class
  204.             //HidD_GetHidGuid(out guid);
  205.  
  206.             // get a handle to all devices that are part of the HID class
  207.             // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
  208.             IntPtr hDevInfo = SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);
  209.  
  210.             // create a new interface data struct and initialize its size
  211.             SP_DEVICE_INTERFACE_DATA diData = new SP_DEVICE_INTERFACE_DATA();
  212.             diData.cbSize = (uint)Marshal.SizeOf(diData);
  213.  
  214.             // get a device interface to a single device (enumerate all devices)
  215.             while (SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
  216.             {
  217.                 UInt32 size;
  218.  
  219.                 // Get Device Name
  220.                 string deviceName = GetClassNameFromGuid(diData.InterfaceClassGuid);
  221.  
  222.                 // get the buffer size for this device detail instance (returned in the size parameter)
  223.                 SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);
  224.  
  225.                 // create a detail struct and set its size
  226.                 SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
  227.                 diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);
  228.  
  229.                 // actually get the detail struct
  230.                 if (SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
  231.                 {
  232.                     MessageBox.Show("Battery " + (index + 1) + " Device Path: " + diDetail.DevicePath);
  233.  
  234.                     // open a read/write handle to our device using the DevicePath returned
  235.                     SafeFileHandle mHandle = CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, EFileAttributes.Overlapped, IntPtr.Zero);
  236.  
  237.                     if (!mHandle.IsInvalid)
  238.                     {
  239.                         bool result = false;
  240.  
  241.                         try
  242.                         {
  243.                             ulong time = 0, tag = 0, bytes = 0;
  244.                             result = DeviceIoControl(mHandle, CTL_CODE(FILE_DEVICE_BATTERY, 0x10, METHOD_BUFFERED, FILE_ANY_ACCESS),
  245.                                 ref time, (uint)Marshal.SizeOf(time), ref tag, (uint)Marshal.SizeOf(tag), ref bytes, null);
  246.                             if (result)
  247.                             {
  248.                                 BATTERY_QUERY_INFORMATION bqi = new BATTERY_QUERY_INFORMATION();
  249.                                 bqi.AtRate = 0;
  250.                                 bqi.BatteryTag = tag;
  251.                                 //bqi.InformationLevel = 
  252.  
  253.                                 MessageBox.Show("Tag: " + tag.ToString() + " and bytes: " + bytes);
  254.  
  255.                                 uint len = 0;
  256.                                 uint nInBufferSize = (uint)Marshal.SizeOf(bqi);
  257.                                 BATTERY_INFORMATION bi = new BATTERY_INFORMATION();
  258.                                 uint nOutBufferSize = (uint)Marshal.SizeOf(bqi);
  259.                                 result = false;
  260.  
  261.                                 result = DeviceIoControl(mHandle, CTL_CODE(FILE_DEVICE_BATTERY, 0x11, METHOD_BUFFERED, FILE_ANY_ACCESS),
  262.                                    ref bqi, nInBufferSize, ref bi, nOutBufferSize, ref len, IntPtr.Zero);
  263.  
  264.                                 if (result)
  265.                                 {
  266.                                     MessageBox.Show("Bytes Return: " + len.ToString());
  267.                                     MessageBox.Show("Design Capacity: " + bi.DesignCapacity);
  268.                                     MessageBox.Show("Full Charge Capacity: " + bi.FullChargeCapacity);
  269.                                 }
  270.                                 else
  271.                                 {
  272.                                     MessageBox.Show("No Result");
  273.                                 }
  274.                             }
  275.                             else
  276.                             {
  277.                                 MessageBox.Show("Battery Query Information Not processed");
  278.                             }
  279.                         }
  280.                         finally
  281.                         {
  282.                             //Marshal.FreeHGlobal(pInBuffer);
  283.                             //Marshal.FreeHGlobal(pOutBuffer);
  284.                         }
  285.  
  286.                     }
  287.                     else
  288.                     {
  289.                         MessageBox.Show("In-valid File Handle");
  290.                     }
  291.  
  292.                     mHandle.Close();
  293.  
  294.                     int errCode = Marshal.GetLastWin32Error();
  295.                     MessageBox.Show("Win32 Error: " + errCode.ToString());
  296.                 }
  297.                 else
  298.                 {
  299.                     // failed to get the detail struct
  300.                     throw new Exception("SetupDiGetDeviceInterfaceDetail failed on index " + index);
  301.                 }
  302.  
  303.                 // move to the next device
  304.                 index++;
  305.             }
  306.  
  307.             // clean up our list
  308.             SetupDiDestroyDeviceInfoList(hDevInfo);
  309.  
  310.             // if we didn't find a Wiimote, throw an exception
  311.             //if (!found)
  312.             //    throw new Exception("Wiimote not found in HID device list.");
  313.         }
  314.  
  315.         private static uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access)
  316.         {
  317.             return (uint)(((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method));
  318.         }
  319.  
  320.         #endregion
  321.  
Thanks,
Sanjay


@PsychoCoder
Nov 26 '12 #3
PsychoCoder
465 Expert Mod 256MB
Moved to C# forum, also, what problems/errors are you having with this code?
Nov 26 '12 #4
Hi,

I have issue related to the Windows API "DeviceIOControl" calling and its declaration. Actully, this API not returning value of "Battery_Information" object. I need value of properties "DesignCapacity" and "FullChargeCapacity" from this object.

I have called this API "DevieIOControl" in method "ConnectWithDevice".

You can also have suggest with different approach to get the value of properties "DesignCapacity" and "FullChargeCapacity".

Thanks,
Sanjay
Nov 26 '12 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: ewoo | last post by:
I'm trying to write a wrapper in csharp to wrap DeviceIoControl() win32 method for IOCTL_VIDEO_QUERY_DISPLAY_BRIGHTNESS control code--without much luck. I've seen lots of examples out there for...
10
by: Maria | last post by:
Hi all ! :) I am trying to find a way to return the battery level of a notebook or laptop or any mobile device (but to make it simple a laptop would be fine). I am trying to do this because I'm...
2
by: Ken Allen | last post by:
I am looking for information on using the Win32 API procedure, or its equivalent in C#. I have looked but can find no satisfactory references. I am working on an existing product that has a few...
2
by: Michael Allen | last post by:
I would like to perform something similar to the below function in C# .NET. The C++ below code is from a Microsoft DDK sample driver application. Specifically, I would like to perform Device I/O...
3
by: Jacky | last post by:
Hi, I am trying to make network card interface with VB.NET 2002. I use DeviceIOControl-function. I have tried to define inbuffer and outbuffer using byte array and it's pointer. The second I...
1
by: Pixie | last post by:
I am trying to query the change journal using the deviceIOControl API. The API doesn't return an error, but all of the values in the output buffer are zero, and they shouldn't be. My code is below. I...
0
by: Pixie | last post by:
We are successfully getting a handle to a drive using createfile then using that handle to query the change journal using DeviceIOControl with the paramter FSCTL_QUERY_USN_DATA. However when we try...
1
by: Juan Pedro Gonzalez | last post by:
Helo, I'm having problems here with the input buffer.... Ive defined the API call as: <System.Runtime.InteropServices.DllImport("kernel32", SetLastError:=True)> _ Private Shared Function...
4
by: =?Utf-8?B?TWFyaW5h?= | last post by:
Does any know any sample of how to do a basic DeviceIoControl with something like IOCTL_BATTERY_GETSYSTEMPOWERSTATUSEX2 in C# I have been stuck all week :( and google doesnt yield anything of...
23
by: kid joe | last post by:
Hi all, Sorry this is a bit off-topic... but I do write a good amount of C code on my laptop so there is a link... Basically, it's a question about laptop batteries. About ten days ago, I...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.