2013-08-30 210 views
2

SetCommTimeouts和GetCommTimeouts是kernel32中的函數,用於在與設備通信時設置和獲取超時。在並行端口上使用SetCommTimeouts失敗

現在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

是的,它的工作原理。如果你想要真正的答案,不要問是/否問題。 –

+0

@HenkHolterman告訴我爲什麼我的SetCommTimeouts失敗,幫我 – castiel

+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端口您的計算機,並行端口去渡渡鳥很長的路過去。並且您安裝的並行端口驅動程序不支持超時,通常僅用於串行端口。如有必要,請詢問您從中獲得並行端口硬件的供應商。

+0

這真的很有幫助,謝謝,舊的運動 – castiel

相關問題