Get the device ID and name

Source: Internet
Author: User
Tags win32 error

Get the device ID and name . NET Framework 3.5Other versions

Updated: November 2007

To get the name of the device, use Dns. The GetHostName property. Typically, the default name is "PocketPC".

Example

This example displays the ID and name of the device in a message box when the form is loaded.

To obtain the device ID or serial number, you must use the platform transfer to access the native Windows CE kerneliocontrol function.

C#vb
Using system;using system.drawing;using system.collections;using system.componentmodel;using System.Diagnostics; Using system.windows.forms;using system.runtime.interopservices;using system.text;namespace DeviceID{//<    Summary>//Summary description for DeviceID.             </summary> public class DeviceID:System.Windows.Forms.Form {public DeviceID () {//            Required for Windows Form Designer Support//InitializeComponent (); Todo:add any constructor code after InitializeComponent call/////<summa        ry>//Clean up any resources being used. </summary> protected override void Dispose (bool disposing) {base.        Dispose (disposing); } #region Windows Form Designer generated code///<summary>//Required method for Designer s Upport-do not modify//the ContenTS of this method with the Code editor. </summary> private void InitializeComponent () {////DeviceID/ /this.            Text = "DeviceID"; This. Load + = new System.EventHandler (this.        Deviceid_load);        } static void Main () {Application.Run (New DeviceID ());        } #endregion private static Int32 method_buffered = 0;        private static Int32 file_any_access = 0;        private static Int32 File_device_hal = 0x00000101;        Private Const Int32 error_not_supported = 0x32;        Private Const Int32 Error_insufficient_buffer = 0x7A; private static Int32 Ioctl_hal_get_deviceid = ((File_device_hal) << 16) | ((file_any_access) << 14) | ((+) << 2) |        (method_buffered);             [DllImport ("Coredll.dll", Setlasterror=true)] private static extern bool KernelIoControl (Int32 Dwiocontrolcode, IntPtr Lpinbuf, Int32 ninbufsize, byte[] lpoutbuf, Int32 noutbufsize, ref Int32 lpbytesreturned); private static string Getdeviceid () {//Initialize the output buffer to the size of a//Wi            N32 device_id structure.            byte[] Outbuff = new BYTE[20];            Int32 dwoutbytes;            bool done = false; Int32 nbuffsize = Outbuff.            Length;  Set deviceid.dwsize to size of buffer. Some platforms look at//This field rather than the noutbufsize param of kerneliocontrol//When de            Termining if the buffer is large enough. Bitconverter.getbytes (nbuffsize).              CopyTo (outbuff, 0);            dwoutbytes = 0;            Loop until the device ID is retrieved or an error occurs.  while (! Done) {if (KernelIoControl (Ioctl_hal_get_deviceid, IntPtr.Zero, 0,  Outbuff, nbuffsize, ref dwoutbytes)) {done = true;              } else {int error = Marshal.GetLastWin32Error (); Switch (Error) {case Error_not_supported:throw n                            EW NotSupportedException ("Ioctl_hal_get_deviceid isn't supported on this device",                    New Win32Exception (Error));  Case ERROR_INSUFFICIENT_BUFFER://The BUFFER isn't big enough for the data. The//required size is in the first 4 bytes of the output//buffer (DEVICE                        _id.dwsize).                        Nbuffsize = Bitconverter.toint32 (outbuff, 0);                        Outbuff = new Byte[nbuffsize];  Set deviceid.dwsize to size of buffer.  Some//Platforms look at this field rather than the//noutbufsize param of   KernelIoControl when                     Determining if the buffer is large enough. Bitconverter.getbytes (nbuffsize).                        CopyTo (outbuff, 0);                    Break                    Default:throw New Win32Exception (Error, "unexpected error");            }}}//Copy The elements of the DEVICE_ID structure.            Int32 Dwpresetidoffset = Bitconverter.toint32 (Outbuff, 0x4);            Int32 dwpresetidsize = Bitconverter.toint32 (Outbuff, 0x8);            Int32 Dwplatformidoffset = Bitconverter.toint32 (Outbuff, 0xc);            Int32 dwplatformidsize = Bitconverter.toint32 (Outbuff, 0x10);            StringBuilder sb = new StringBuilder ();                 for (int i = Dwpresetidoffset; I < Dwpresetidoffset + dwpresetidsize; i++) {sb.            Append (String.Format ("{0:x2}", Outbuff[i]); } sb.            Append ("-");        for (int i = Dwplatformidoffset;         I < Dwplatformidoffset + dwplatformidsize; i + +) {sb.            Append (String.Format ("{0:x2}", Outbuff[i]); } return SB.        ToString ();                private void Deviceid_load (object sender, System.EventArgs e) {try {                Show the device ID.                String Strdeviceid = Getdeviceid ();                MessageBox.Show ("Device ID:" + Strdeviceid);                Show the device name.                String devicename = System.Net.Dns.GetHostName ();            MessageBox.Show ("Device Name:" + devicename); } catch (Exception ex) {MessageBox.Show (ex.            Message.tostring ()); }        }    }}
Compiling code

This example needs to reference the following namespaces:

    • System

    • System.ComponentModel

    • System.Runtime.InteropServices

    • System.Text

    • System.Windows.Forms

Reliable Programming

The following table lists the native kerneliocontrol function parameters. All parameters are 32 bits.

Parameters

Win32 type

Managed types

Typical values

Dwiocontrolcode

DWORD

Int32

Ioctl_hal_get_deviceid

Lpinbuf

LPVoid

IntPtr

IntPtr. Zero(no input data required)

Ninbufsize

DWORD

Int32

0 (no input data required)

Lpoutbuf

LPVOID*

Int32

A byte array with 20 elements (the size of thedevice_id structure is 20 bytes)

Noutbufsize

DWORD

Int32

20

lpbytesreturned

Lpword

RefInt32

0

The LPOUTBUF parameter has the following structure:

C#vb
struct device_id{    int dwsize;    int dwpresetidoffset;    int dwpresetidbytes;    int dwplatformidoffset;    int dwplatformidbytes;}
Return values and error handling

If the device ID is copied to the output buffer, thekerneliocontrol function returns true, otherwise it returns false. If KernelIoControl fails, call the managed GetLastWin32Error method to get the Win32 error code. The error code may be any of the following code:

    • Error_not_supported-Indicates that the device does not execute Ioctl_hal_get_deviceid control code.

    • Error_insufficient_buffer-Indicates that the output buffer is not large enough to accommodate the device ID. The required number of bytes specified by dwsize in the device_id structure is returned in the first four bytes of the output buffer. If this error occurs, reassign the output buffer to the size specified by dwsize, and then call KernelIoControlagain.

Please seeTaskHow to: Get Device memoryOther resourcesinteroperability in the. NET Compact Framework

Get the device ID and name

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.