Pergunta

SetCommTimeouts and GetCommTimeouts are the function in kernel32 to set and get timeout when communicate with devices.

Now GetCommTimeouts works for me, but SetCommTimeouts returns error code 87 which indicates parameter error.

Now my question is whether this SetCommTimeouts works when it talks to a parallel port?

If so what can do I to fix it?

[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
Foi útil?

Solução

Your declaration for CreateFile() is quite wrong and can never work in 64-bit mode. Since you don't do any of the required error checking and just keep plowing on, the next call that will fail is your SetCommTimeouts() call. It will complain about getting a bad handle value. Make it look like this instead:

[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);

Proper error handling looks like this:

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();

Additional failure modes are your machine not having a LPT1 port, parallel ports went the way of the dodo a long time ago. And the parallel port driver you have installed not supporting timeouts, it is normally only used for serial ports. Ask the vendor from which you obtained the parallel port hardware for support if necessary.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top