Skip to content

Commit 5420b79

Browse files
committed
Fix corrupted characters at the end of some devices manufacturer strings
I guess the API function signature did not work properly. Part of #17.
1 parent ab9ae34 commit 5420b79

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

Project/Hid/HidDevice.cs

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -134,11 +134,7 @@ private void Construct(IntPtr hRawInputDevice)
134134
}
135135

136136
//Get manufacturer string
137-
StringBuilder manufacturerString = new StringBuilder(256);
138-
if (Win32.Function.HidD_GetManufacturerString(handle, manufacturerString, manufacturerString.Capacity))
139-
{
140-
Manufacturer = manufacturerString.ToString();
141-
}
137+
GetManufacturerString(handle);
142138

143139
//Get product string
144140
GetProductString(handle);
@@ -202,6 +198,26 @@ private void Construct(IntPtr hRawInputDevice)
202198
}
203199
}
204200

201+
/// <summary>
202+
///
203+
/// See: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/hidsdi/nf-hidsdi-hidd_getmanufacturerstring
204+
/// </summary>
205+
private unsafe void GetManufacturerString(SafeHandle aHandle)
206+
{
207+
// The API returns "NULL-terminated wide character string", on Windows I guess that means 16-bits characters.
208+
const int KBufferSize = 256; // Allocate a buffer big enough for 128 characters which is already more than the max 126 characters an USB device can provide.
209+
byte[] buffer = new byte[KBufferSize]; // We use new and fixed rather than stackalloc as it makes it easier to convert to string later
210+
fixed (byte* ptr = buffer)
211+
{
212+
if (Windows.Win32.PInvoke.HidD_GetManufacturerString(aHandle, ptr, (uint)buffer.Length) == Windows.Win32.K.TRUE)
213+
{
214+
// Assuming our wide character string is Unicode encoded we convert our buffer to a string object.
215+
// Also make sure we remove null characters at the end.
216+
Manufacturer = System.Text.Encoding.Unicode.GetString(buffer).TrimEnd('\0');
217+
}
218+
}
219+
}
220+
205221
/// <summary>
206222
///
207223
/// See: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/hidsdi/nf-hidsdi-hidd_getproductstring

Project/Hid/NativeMethods.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22

33
HidP_GetUsageValueArray
44
HidD_GetProductString
5+
HidD_GetManufacturerString

0 commit comments

Comments
 (0)