Reputation: 433
I am working on a Windows Forms Application that should get data from a USB Scale. The USB scale is handled like a Keyboard. If someone puts something on the scale, the scale starts to type the weight String like a USB Keyboard. Before, I'd let the scale type the Weight String into a Textbox by clicking into textBox in the Forms App. But now I need to obtain the weight string intern without letting the Scale write directly into a textBox. So that the Program can process the data from the scale while it is in Background.
So at first I think I have to choose a Device for the Input. (something like Keyborad on Com Port XY) So I need to create a List including all Input Devices. How do I do this in C# .Net?
I already tried:
string[] devices = GetRawInputDeviceList;
textBox1.Text = devices[0];
textBox2.Text = devices[1];
But this is not working. Could maybe someone tell me how to do that? Or what do you guys think is the best way to solve my Problem? Please Help!
Upvotes: 1
Views: 4576
Reputation: 433
I want to inform you that the following code helped me solving my Problem. You will need Mike O’Brien’s USB HID library. You can download it in VisualStudio (NuGet Packages) or here: https://github.com/mikeobrien/HidLibrary
using System;
using System.Linq;
using System.Text;
using HidLibrary;
namespace HIDProject
{
class Program
{
private const int VendorId = 0x0801;
private const int ProductId = 0x0002;
private static HidDevice _device;
static void Main()
{
_device = HidDevices.Enumerate(VendorId, ProductId).FirstOrDefault();
if (_device != null)
{
_device.OpenDevice();
_device.Inserted += DeviceAttachedHandler;
_device.Removed += DeviceRemovedHandler;
_device.MonitorDeviceEvents = true;
_device.ReadReport(OnReport);
Console.WriteLine("Reader found, press any key to exit.");
Console.ReadKey();
_device.CloseDevice();
}
else
{
Console.WriteLine("Could not find reader.");
Console.ReadKey();
}
}
private static void OnReport(HidReport report)
{
if (!_device.IsConnected) { return; }
var cardData = new Data(report.Data);
Console.WriteLine(!cardData.Error ? Encoding.ASCII.GetString(cardData.CardData) : cardData.ErrorMessage);
_device.ReadReport(OnReport);
}
private static void DeviceAttachedHandler()
{
Console.WriteLine("Device attached.");
_device.ReadReport(OnReport);
}
private static void DeviceRemovedHandler()
{
Console.WriteLine("Device removed.");
}
}
}
Upvotes: 2