C# How to adding objects to listbox and displaying them with a specific text

626 views Asked by At

I used to do this in delphi, i.e. add objects and items at the same time to a listbox:

function TMainForm.JvHidDeviceController1Enumerate(HidDev: TJvHidDevice;
  const Idx: Integer): Boolean;
var
  N: Integer;
  Dev: TJvHidDevice;
begin
  VID := JvValidateEdit1.Value;
  PID := JvValidateEdit2.Value;
  // MessageDlg(IntToStr(DeviceRadioGroup.ItemIndex), mtInformation, mbOKCancel, 0);
  If (HidDev.Attributes.VendorID = VID) And
    (HidDev.Attributes.ProductID = PID) Then
  begin
    N := ListBox1.Items.Add('dsn: ' + HidDev.SerialNumber);
    JvHidDeviceController1.CheckOutByIndex(Dev, Idx);
    ListBox1.Items.Objects[N] := Dev;
    DeviceMemo.Lines.Append(HidDev.SerialNumber +
      ' : connected(enumerated)   - ' + (TimeToStr(Now)));
    InfoBtn.Enabled := true;
    WriteBtn.Enabled := true;
  end;
  Result := true;
end;

I am suing HIDLibrary from Mike, and I have more than one device, each with a different serial number that I need to add to the listbox, the problem is that I don't know if it is possible to add objects to the listbox and display them in a different text in C# as I used to do it in delphi, the default text shows the path of the device when i add HidDevice object to listbox, while i want only serialNo to be displayed. I extract the serialNo. of each valid HID device and in one line I insert it to AllValidHIDDevices using the index resulting from adding that serialNo. to the listbox, so that each HID device is bound to its serialNo. and when I click on the serial number, I am actually retrieving the HID device with that serial number software snapshot

HidDevice CurrentHIDDevice;
List<HidDevice> AllValidHIDDevices = new List<HidDevice>();
IEnumerable<HidDevice> USBDevices;

private void timer1_Tick(object sender, EventArgs e)
{

    AllValidHIDDevices.Clear();
    listBox1.Items.Clear();

    USBDevices = HidDevices.Enumerate(0x0483);

    foreach (HidDevice validHIDDevice in USBDevices.Where(x => x.Attributes.ProductHexId == "0xAB12"))
    {
        byte[] serialNo;

        validHIDDevice.Inserted += deviceInserted;
        validHIDDevice.Removed += deviceRemoved;
        validHIDDevice.MonitorDeviceEvents = true;
        if (validHIDDevice.IsConnected)
        {
            timer1.Stop();
            button1.Enabled = true;
            validHIDDevice.ReadSerialNumber(out serialNo);
            AllValidHIDDevices.Insert(listBox1.Items.Add("Serial Number: " + Encoding.Unicode.GetString(serialNo)), validHIDDevice);
        }
    }
    if (listBox1.Items.Count > 0)
    {
        listBox1.SelectedIndex = 0;
        CurrentHIDDevice = AllValidHIDDevices[listBox1.SelectedIndex];  
    }
}

private void deviceInserted()
{
    this.InvokeEx(x => x.toolStripStatusLabel1.Text = listBox1.Items.Count.ToString() + " device(s) attached");
}

private void deviceRemoved()
{
    foreach (HidDevice validHIDDevice in AllValidHIDDevices)
    {
        if (validHIDDevice.IsOpen)
            validHIDDevice.CloseDevice();
        validHIDDevice.Dispose();
    }
    this.InvokeEx(x => x.toolStripStatusLabel1.Text = "No device(s) attached");
    this.InvokeEx(x => x.listBox1.Items.Clear());
    this.InvokeEx(x => x.button1.Enabled = false);
    this.InvokeEx(x => x.timer1.Start());
}

Once an item is added, I just click on it to select it and interact with it:

    private void listBox1_Click(object sender, EventArgs e)
    {
        try
        {
            if (listBox1.Items.Count > 0 && listBox1.SelectedIndex >= 0)
                CurrentHIDDevice = AllValidHIDDevices[listBox1.SelectedIndex];
        }
        catch
        {
            MessageBox.Show("Selected item is not a USB device!");
        }
    }
1

There are 1 answers

0
elekgeek On

Ok, I will answer this now.

I was using the dll because I downloaded it with NuGet, now I understand why I was unable to modify anything related to HidDevice class, I thought that NuGet downloaded the source code of this library as well and used it, but in the package folder, there is only the dll. Then I removed it and downloaded the source of the library itself from GitHub, learnt how to add it and use it. I just modified the ToString function in HidDevice class as follows:

    public override string ToString()
    {
        byte[] SerialNumber;
        ReadSerialNumber(out SerialNumber);
        string SerialNumberString = "Serial Number = " + Encoding.Unicode.GetString(SerialNumber);

        if (SerialNumberString[0] == '\0')
        {
            return string.Format("VendorID={0}, ProductID={1}, Version={2}, DevicePath={3}",
                                _deviceAttributes.VendorHexId,
                                _deviceAttributes.ProductHexId,
                                _deviceAttributes.Version,
                                _devicePath);
        }
        else
        {
            return SerialNumberString;
        }
    }

The solution is much simpler now.. Thanks to @TaW who pointed it out in the first place.