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/