【问题标题】:Using SetCommTimeouts on parallel port fails在并行端口上使用 SetCommTimeouts 失败
【发布时间】:2013-08-30 09:08:27
【问题描述】:

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

【问题讨论】:

  • 是的,它有效。如果您想要真正的答案,请不要问是/否问题。
  • @HenkHolterman 告诉我为什么我的 SetCommTimeouts 失败,帮帮我
  • 您有一个参数错误,但您没有发布参数。无法回答。贴出代码:功能大纲、导入定义等
  • @HenkHolterman 好的,等一下
  • 看起来不错,但可能会在前面放一个定向 Attr 以确保:, [In] ref LPCOMMTIMEOUTS lpCommTimeouts);

标签: c# kernel parallel-port


【解决方案1】:

您对 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 端口,并行端口在很久以前就像渡渡鸟一样。而且你安装的并口驱动不支持超时,一般只用于串口。如有必要,请向您获得并行端口硬件的供应商寻求支持。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2020-04-03
    • 2018-05-18
    • 2017-01-11
    • 2021-01-04
    • 2021-10-08
    • 2021-11-14
    相关资源
    最近更新 更多