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
答案 0 :(得分:4)
您对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端口,并行端口很久以前就像渡渡鸟一样。并且您安装的并行端口驱动程序不支持超时,它通常仅用于串行端口。如有必要,请询问您从中获得并行端口硬件的供应商。