2

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
4

1 に答える 1

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 ポートがないことです。パラレル ポートはずっと前にドードーのようになりました。また、インストールしたパラレル ポート ドライバはタイムアウトをサポートしていません。通常はシリアル ポートにのみ使用されます。必要に応じて、パラレル ポート ハードウェアを入手したベンダーにサポートを依頼してください。

于 2013-08-30T10:23:40.233 に答える