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
类是一个简单的示例实现,您可能需要根据您的实陗际情况对其进行调整和扩展。