在并行端口上使用SetCommTimeouts失败
本文关键字:SetCommTimeouts 失败 并行端口 | 更新日期: 2023-09-27 18:29:41
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位模式下工作。由于您不进行任何必要的错误检查,只是继续努力,下一个失败的调用是SetCommTimeout()调用。它会抱怨句柄值不正确。让它看起来像这样:
[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端口,并行端口在很久以前就已经过时了。并且您安装的并行端口驱动程序不支持超时,它通常只用于串行端口。如有必要,请向您获得并行端口硬件的供应商寻求支持。