using System;
using System.IO;
using System.Threading;
namespace WinUSBExample
{
class Program
{
static void Main(string[] args)
{
// GUID of the WinUSB device
Guid deviceGuid = new Guid("PUT_YOUR_DEVICE_GUID_HERE");
// Find the device
var devices = WinUsbHelper.GetConnectedDevices(deviceGuid);
if (devices.Count == 0)
{
Console.WriteLine("No WinUSB device found");
return;
}
// Open the device
var device = devices[0];
device.Open();
// Write data to the device
byte[] writeData = { 0x01, 0x02, 0x03 };
device.Write(writeData);
Console.WriteLine("Data written to device: " + BitConverter.ToString(writeData).Replace("-", ""));
// Read data from the device
byte[] readData = new byte[3];
device.Read(readData);
Console.WriteLine("Data read from device: " + BitConverter.ToString(readData).Replace("-", ""));
// Close the device
device.Close();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
}
在上面的示例中,我們首先使用WinUsbHelper.GetConnectedDevices
方法查找連接的WinUSB設備,并打開第一個找到的設備。然后我們使用device.Write
方法向設備寫入數據,使用device.Read
方法從設備讀取數據,最后關閉設備連接。
請注意,您需要將PUT_YOUR_DEVICE_GUID_HERE
替換為您的WinUSB設備的GUID。您還需要定義WinUsbHelper
類來幫助您操作WinUSB設備,這里是一個簡單的實現示例:
using System;
using System.Collections.Generic;
using System.Management;
public static class WinUsbHelper
{
public static List<WinUsbDevice> GetConnectedDevices(Guid deviceGuid)
{
var devices = new List<WinUsbDevice>();
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE DeviceID LIKE 'USB%'"))
{
foreach (var device in searcher.Get())
{
var deviceId = device.GetPropertyValue("DeviceID").ToString();
if (deviceId.Contains(deviceGuid.ToString("B")))
{
devices.Add(new WinUsbDevice(deviceId));
}
}
}
return devices;
}
}
public class WinUsbDevice
{
private string deviceId;
public WinUsbDevice(string deviceId)
{
this.deviceId = deviceId;
}
public void Open()
{
// Implement device open logic here
}
public void Write(byte[] data)
{
// Implement write logic here
}
public void Read(byte[] data)
{
// Implement read logic here
}
public void Close()
{
// Implement device close logic here
}
}
請注意,上面的WinUsbHelper
類是一個簡單的示例實現,您可能需要根據您的實陗際情況對其進行調整和擴展。