2013-07-16 26 views
1

我正在嘗試使用簡單寫入命令將字符串寫入Com5上的內部打印機。 WriteLine方法打印出來很好,但Write不會。以下是我打電話的代碼。它只是調用.NET函數的簡單包裝函數。C#SerialPort WriteLine有效,但不能寫

public static void Write(string printString) 
    { 
    //intialize the com port 
    SerialPort com5 = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One); 
    com5.Handshake = Handshake.XOnXOff; 
    com5.Open(); 

    //write the text to the printer 
    com5.Write(printString); 
    Thread.Sleep(100); 

    com5.Close(); 
    } 

    public static void WriteLine(string printString) 
    { 
    //intialize the com port 
    SerialPort com5 = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One); 
    com5.Handshake = Handshake.XOnXOff; 
    com5.Open(); 

    //write the text to the printer 
    com5.WriteLine(printString); 
    Thread.Sleep(100); 

    com5.Close(); 
    } 
+1

爲什麼'WriteLine()'對你不好?否則我不知道你的問題是什麼。 – CSJ

+0

是否有可能打印機正在緩衝,直到有完整的一行?如果在'Write'之後調用'WriteLine',會發生什麼? –

+0

您需要避免重複打開和關閉端口。對於SerialPort.Close()的MSDN文章特別警告這一點。在代碼中避免非常危險的Thread.Sleep()也是一個好方法。 –

回答

1

WriteLine會在字符串中附加一個新的行字符。也許這個「刷新」緩衝區讓打印機響應輸入。

1

你是如何找到它的書面或不是?我的意思是如果另一端是一個應用程序正在監聽?那麼它是在尋找一個CrLf?你可以添加新行到字符串,並將其發送到寫並看到?如果這有效?因爲除了新行外,Coz Writeline和Write都應該類似。

+0

是的,這工作,但我需要能夠寫入文本,而不必去下一行,以便我可以在同一行上追加各種字符串。這絕對給了我一些工作。 – silastk

+0

你是如何做到這一點的? @silastk Environment.Newline和發送字符串的結束? –

0

SerialPort對象使用Stream對象在較低級別進行讀寫操作。它可以通過屬性BaseStream訪問。 也許如果你在寫入指令之前刷新數據流,它會強制更新數據流。

... 
//write the text to the printer 
com5.Write(printString); 
com5.BaseStream.Flush(); 
Thread.Sleep(100); 
... 

艾麗西亞。