获取设备 ID 和名称

获取设备 ID 和名称

.NET Framework 3.5

其他版本

更新:2007 年 11 月

要获取设备的名称,请使用 Dns.GetHostName 属性。通常情况下,默认名称为“PocketPC”。

示例

本示例在加载窗体时在消息框中显示设备的 ID 和名称。

要获取设备 ID 或序列号,您必须使用平台调用来访问本机 Windows CE KernelIoControl 函数。

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
            //
        }

        /// <summary>
        /// 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 support - 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)
            | ((21) << 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
            // Win32 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 determining 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 new NotSupportedException(
                            "IOCTL_HAL_GET_DEVICEID is not supported on this device",
                            new Win32Exception(error));

                    case ERROR_INSUFFICIENT_BUFFER:

                        // The buffer is not 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());
            }
        }
    }
}

编译代码

此示例需要引用下面的命名空间:

可靠编程

下表列出了本机 KernelIoControl 函数参数。所有参数均是 32 位。


参数


Win32 类型


托管类型


典型值


dwIoControlCode


DWORD


Int32


IOCTL_HAL_GET_DEVICEID


lpInBuf


LPVOID


IntPtr


IntPtr.Zero(不要求输入数据)


nInBufSize


DWORD


Int32


0(不要求输入数据)


lpOutBuf


LPVOID*


Int32


含 20 个元素的Byte 数组(DEVICE_ID 结构的大小为 20 字节)


nOutBufSize


DWORD


Int32


20


lpBytesReturned


LPWORD


refInt32


0

lpOutBuf 参数具有以下结构:

C#

VB

struct DEVICE_ID
{
    int dwSize;
    int dwPresetIDOffset;
    int dwPresetIDBytes;
    int dwPlatformIDOffset;
    int dwPlatformIDBytes;
}

返回值和错误处理

如果将设备 ID 复制到了输出缓冲区,KernelIoControl 函数返回 true;否则,它会返回 false。如果 KernelIoControl 失败,请调用托管GetLastWin32Error 方法以获取 Win32 错误代码。错误代码可能是下列代码中的任意一种:

  • ERROR_NOT_SUPPORTED - 指示设备不执行 IOCTL_HAL_GET_DEVICEID 控制代码。
  • ERROR_INSUFFICIENT_BUFFER - 指示输出缓冲区不够大,无法容纳设备 ID。由 DEVICE_ID 结构中的 dwSize 指定的所需字节数在输出缓冲区的前四个字节中返回。如果发生此错误,请将输出缓冲区重新分配为 dwSize 指定的大小,然后再次调用 KernelIoControl

请参见

任务

如何:获取设备内存

其他资源

.NET Compact Framework 中的互操作性

时间: 2024-08-01 00:53:38

获取设备 ID 和名称的相关文章

ios获取设备信息总结

1.获取设备的信息 1 UIDevice *device = [[UIDevice alloc] int]; 2 NSString *name = device.name; //获取设备所有者的名称 3 NSString *model = device.name; //获取设备的类别 4 NSString *type = device.localizedModel; //获取本地化版本 5 NSString *systemName = device.systemName; //获取当前运行的系统

获取设备号

//获取设备id号 UIDevice *device = [UIDevice currentDevice];//创建设备对象 NSString *deviceUID = [[NSString alloc] initWithString:device.identifierForVendor.UUIDString]; NSLog(@"************************************************************************************

Linux下获取设备pci ID的方法

有的时候,开发时需要用到设备的pci ID,如用dpdk来绑定某个网卡,需要用网卡的pci ID.下面有一些方法是可以获取pci ID的. 1.使用lspci命令. 如 02:00.0 USB controller: Intel Corporation 82371AB/EB/MB PIIX4 USB 02:01.0 Ethernet controller: Intel Corporation 82545EM Gigabit Ethernet Controller (Copper) (rev 01

黄聪:wordpress如何获取当前分类页面的ID、名称、别名(slug)

<? global $wp_query; $cat_ID = get_query_var('cat'); $category = get_category($cat_ID); echo $category->slug; ?> get_category()    根据分类ID获得指定分类全部信息,以数组或是对象的形式返回,以下是该函数的返回值示例: stdClass Object( //ID 分类和标签混编 [term_id] => 5 //分类名 [name] => Cat

Windows Phone 8 获取设备名称

通过使用Microsoft.Phone.Info.DeviceStatus类,我们可以获取设备的一些信息,如设备厂商,设备名称等.通过Microsoft.Phone.Info.DeviceStatus.DeviceName可以获取设备的名称,但是这个名称通常并不是我们熟悉的设备名称,而是该设备标识名称.例如:Lumia520,通过上述接口获取的设备标识是“RM-914_apac_prc_227”,大家对“Lumia520"是比较熟悉,而对于通过接口直接获取的“RM-914_apac_prc_22

根据进程名称获取进程id

# -*- conding:utf-8-*- import subprocess def getpid_windows(process_name):    """利用cmd_str = tasklist|find /i "xdict.exe" 来查找windows平台的进程id"""    cmd_line = 'tasklist|find /i "%s"' %process_name    pp = su

ECSHOP在商品详细页面上获取该商品的顶级分类id和名称

在 goods.php 文件, 找到 $smarty->assign('goods', $goods); 在它上面增加下面代码: 方法一: $cat_arr = get_parent_cats($goods['cat_id']); foreach ($cat_arr AS $val) { $goods['topcat_id']=$val['cat_id']; $goods['topcat_name']=$val['cat_name']; } 方法二: $cat_arr = get_parent_

获取设备IMEI ,手机名称,系统SDK版本号,系统版本号

1.获取设备IMEI TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String IMEIs = tm.getDeviceId() ; 需要的权限 <uses-permission android:name="android.permission.READ_PHONE_STATE" > </uses-permission> 运行结果: 8

iOS ---------- 获取设备的各种信息

一.目录结构: 获取屏幕宽度与高度 获取设备版本号 获取iPhone名称 获取app版本号 获取电池电量 获取当前系统名称 获取当前系统版本号 获取通用的唯一识别码UUID 获取当前设备IP 获取总内存大小 获取当前可用内存 获取精准电池电量 获取电池当前的状态(共有4种状态) 获取设备当前的语言 二.具体内容 1. 获取屏幕宽度与高度 /// 屏幕宽度 + (CGFloat)getDeviceScreenWidth { return [UIScreen mainScreen].bounds.s