您的位置:首页 > 编程语言 > C#

C# WPD PortableDeviceApiLib获取便携设备列表

2017-07-29 21:01 483 查看
    本文主要参考自: http://blogs.msdn.com/b/wpdblog/archive/2007/11/26/creating-a-temperature-sensor-gadget-for-windows-sidebar.aspx
    在win7系统中插入的平板、手机等,有的被识别为便携设备,而不是可移动磁盘,这种情况设备的获取与普通磁盘不同。

使用PortableDeviceApiLib可以获取接入的设备信息。

    在实际查询使用PortableDeviceApiLib过程中,其方法GetDevices和GetDeviceFriendlyName并不能为c#正确使用。这其中牵扯到com与.net间能否正确使用的问题。不再详述(因为我也不太明白



 解决方案:

对PortableDeviceApiLib进行改造。使用C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools下的ildasm.exe,打开项目obj/Debug路径下的Interop.PortableDeviceApiLib.dll文件,使用文件->转储,转存为*.il文件。使用文本编辑器,修改

GetDevices

修改前:

      instance void  GetDevices([in][out] string&  marshal( lpwstr) pPnPDeviceIDs,

修改后:

      instance void  GetDevices([in][out] string[]  marshal([]) pPnPDeviceIDs,
GetDeviceFriendlyName

修改前:

    [in][out] uint16& pDeviceFriendlyName

修改后:

    [in][out] uint16[] marshal( []) pDeviceFriendlyName 

修改完毕,保存。

控制台执行C:\Users\Sun\Desktop>c:\windows\microsoft.NET\framework\v4.0.30319\ilasm.exe
/dll/resource=PortableDeviceApiLib.res PortableDeviceApiLib.il进行编译。

在桌面会生成相应的dll文件,将此文件拷贝到项目obj/Debug文件夹下。

c#代码:

[html]
view plain
copy

<pre class="csharp" name="code">PortableDeviceManager devMgr = new PortableDeviceManager();  
            uint cDevices = 0;  
            devMgr.GetDevices(null, ref cDevices);  
            if (cDevices > 0)  
            {  
                string[] deviceIDs = new string[cDevices];  
                devMgr.GetDevices(deviceIDs, ref cDevices);  
                foreach (string dev in deviceIDs)  
                {  
                    string deviceName = getFriendlyName(dev);  
                }  
                  
            }  

[html]
view plain
copy

<pre class="csharp" name="code">//根据设备id获取设备名称  

[csharp]
view plain
copy

public string getFriendlyName(string deviceID)  
        {  
            List<string> msgs = new List<string>();  
            uint nameLength = 0;  
            PortableDeviceManager devMgr = new PortableDeviceManager();  
            devMgr.GetDeviceFriendlyName(deviceID, null, ref nameLength);  
            ushort[] nameBuffer = new ushort[nameLength];  
            devMgr.GetDeviceFriendlyName(deviceID,  nameBuffer, ref nameLength);  
            string friendlyName = "";  
            foreach (ushort letter in nameBuffer)  
            {  
                if (letter != 0)  
                    friendlyName += (char)letter;  
            }  
            return friendlyName;  
        } 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: