You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于kernel32.dll的C# .NET USB打印机通信异常求助

USB打印机双向通信问题

我尝试很久都没法实现通过USB和打印机通信,网上相关的解决方案很少。我的目标是实现USB与打印机的双向通信,发送指令并接收返回数据。目前用第三方工具PrintFile可以成功给打印机发送二进制文件,而且通过Wireshark-usbcap能抓到打印机的响应包,说明打印机本身支持USB响应请求。

我参考了ChatGPT和Stack Overflow的相关帖子,基于生成的代码修改后,当前代码如下:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CreateFile(
    [MarshalAs(UnmanagedType.LPTStr)] string filename,
    UInt32 desiredaccess, UInt32 sharemode, IntPtr securityattributes,
    UInt32 creationdisposition, UInt32 flagsandattributes, 
    IntPtr templatefile);

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool WriteFile(IntPtr hFile, byte[] lpBuffer,
    uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten,
    [In] ref System.Threading.NativeOverlapped lpOverlapped);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer,
    uint nNumberOfBytesToRead, out uint nNumberOfBytesRead, [In] ref System.Threading.NativeOverlapped lpOverlapped);

public static bool WriteToPort(string port, ref byte[] data)
{
    IntPtr hPrinter = IntPtr.Zero;
    bool success = true;
    uint bytesWritten = 0;

    hPrinter = CreateFile(port,
                        (UInt32)(FileAccess.ReadWrite),
                        (UInt32)(FileShare.ReadWrite),
                        IntPtr.Zero,
                        (UInt32)FileMode.OpenOrCreate,
                        (UInt32)(FileAttribute.Normal),
                        IntPtr.Zero);

    System.Threading.NativeOverlapped lpOverlapped = new System.Threading.NativeOverlapped();
    success = WriteFile(hPrinter, data, (uint)data.Length, out bytesWritten, ref lpOverlapped);

    CloseHandle(hPrinter);

    return success && bytesWritten > 0;
}

调用WriteToPort时,端口参数传的是"USB001",数据是用于请求信息的4字节数组。运行代码后,bytesWritten显示为4,success也为true,但打印机完全没反应(正常接收指令时屏幕会亮起),而且Wireshark-usbcap抓不到 outgoing数据包。但用PrintFile工具时,能正常抓到双向数据包。

内容的提问来源于stack exchange,提问作者Robin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:05:01