c# - 在并行端口上使用 SetCommTimeouts 失败

标签 c# kernel parallel-port

SetCommTimeouts 和 GetCommTimeouts 是 kernel32 中的函数,用于设置和获取与设备通信时的超时时间。

现在 GetCommTimeouts 对我有用,但 SetCommTimeouts 返回错误代码 87,表示参数错误。

现在我的问题是这个 SetCommTimeouts 在与并行端口通信时是否有效?

如果是这样,我该如何解决它?

[DllImport("kernel32.dll")]
private static extern bool SetCommTimeouts(IntPtr hFile, ref LPCOMMTIMEOUTS lpCommTimeouts);
[DllImport("kernel32.dll ")]
private static extern int CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);

[StructLayout(LayoutKind.Sequential)]
private struct LPCOMMTIMEOUTS
{
    public UInt32 ReadIntervalTimeout;
    public UInt32 ReadTotalTimeoutMultiplier;
    public UInt32 ReadTotalTimeoutConstant;
    public UInt32 WriteTotalTimeoutMultiplier;
    public UInt32 WriteTotalTimeoutConstant;
}
private const uint GENERIC_WRITE = 0x40000000;
private const int OPEN_EXISTING = 3;
PHandler = CreateFile("LPT1", GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
IntPtr hnd = new System.IntPtr(PHandler);
LPCOMMTIMEOUTS lpcto = new LPCOMMTIMEOUTS();
Boolean bb = SetCommTimeouts(hnd, ref lpcto);
Console.WriteLine(bb); // get false here

最佳答案

您对 CreateFile() 的声明是完全错误的,并且永远无法在 64 位模式下工作。由于您没有执行任何必需的错误检查,只是继续努力,因此下一个失败的调用是 SetCommTimeouts() 调用。它会提示得到一个错误的句柄值。让它看起来像这样:

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern IntPtr CreateFile(
    string FileName,
    FileAccess DesiredAccess,
    FileShare ShareMode,
    IntPtr SecurityAttributes,
    FileMode CreationDisposition,
    FileAttributes FlagsAndAttributes,
    IntPtr TemplateFile);

正确的错误处理如下所示:

IntPtr hnd = CreateFile("LPT1", FileAccess.Write, FileShare.None, IntPtr.Zero, 
                        FileMode.Open, FileAttributes.Normal, IntPtr.Zero);
if (hnd == (IntPtr)-1) throw new System.ComponentModel.Win32Exception();

其他故障模式是您的机器没有 LPT1 端口,并行端口很久以前就走上了渡渡鸟的道路。并且您安装的并行端口驱动程序不支持超时,它通常仅用于串行端口。如有必要,请向您提供并行端口硬件的供应商寻求支持。

关于c# - 在并行端口上使用 SetCommTimeouts 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18529083/

相关文章:

c - "#include <asm/io.h>"导致 "error: asm/io.h: No such file or directory"

c# - 使用 async/await 和 TaskCompletionSource 的奇怪堆栈跟踪增长

c# - 如何从 App_Code 引用 ASP.net MasterPage

c# - 分组 Linq 问题,无法正确处理

c - 如何使用有故障的内核模块 - FC19 使系统崩溃?

serial-port - 以编程方式控制英国的电源 socket

c# - 无法加载文件或程序集 'itextsharp' 或其依赖项之一

c - 如何在 Linux 内核中进行分析或使用 perf_event*.[hc] 框架?

c - 如何使用内核头文件编译用户空间程序

C# - 读取并行端口状态(简单的按钮开关)