Working With Devices: Getting Friendly Class Names

Ok, so once again I haven't posted in a long time. I'd like to say that I've decided to post at least once per week. Hopefully that will stay true. Given my past track record, your guess is as good as mine.

So, this time around we are going to get the friendly names for our device classes. Previously we may have retrieved a device class name of 'net'. Looking in the Device Manager we only find 'Network adapters'. That is the friendly name and the name you'll likely want to display.

So here is the code using the SetupDiGetClassDescription function.

Private Declare Auto Function SetupDiGetClassDescription Lib "setupapi.dll" (ByRef ClassGuid As Guid, ByVal ClassDescription As System.Text.StringBuilder, ByVal ClassDescriptionSize As Integer, ByRef RequiredSize As IntPtr) As Boolean

'Returns the Class Description (Friendly name for the Class is a better way to put it)
Public Function GetClassDescription(ByVal ClassName As String) As String

'The First section we get the length that we need

Dim intSize As IntPtr
Dim ClassGuid As Guid = GetClassGuid(ClassName)
Dim Result As Boolean = SetupDiGetClassDescription(ClassGuid, Nothing, 0, intSize)
If Not Result Then
Dim intErrorCode As Integer = Marshal.GetLastWin32Error
If intErrorCode <> 122 Then '122 is insufficient buffer (We expect it to happen)
Throw New Win32Exception(intErrorCode)
End If
End If


'The Second section we instantiate an object of the given size and get the Description

Dim ClassDesc As New System.Text.StringBuilder(intSize.ToInt32)
Result = SetupDiGetClassDescription(ClassGuid, ClassDesc, intSize.ToInt32, intSize)
If Not Result Then
Throw New Win32Exception(Marshal.GetLastWin32Error)
End If
Return ClassDesc.ToString
End Function

The above code seems to be pretty typical for these functions. First we get the size of the Class Description and then we get the actual description and return it.

No comments: