while (true)
{
serialPo开发者_运维问答rt1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);
}
private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1);
byte DATA = Convert.ToByte(serialPort1.ReadByte());
Console.WriteLine(DATA);
//MessageBox.Show(Convert.ToString(DATA));
}
I can see serial DATA on console but I do not know how to handle this DATA and show it on textBox etc. what is missing in my code
In addition to @adatapost answer:
Fist:
while(true)
{
serialPort1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);
} ???!!
Hope this is just wrong copy/paste, cause subscribe to the event in infinite while
loop !
Second: it's not clear what you want to see on the screen.
If just symbols the first answer is pretty suitable, if not you shoud read your device documentation (printer, bill counter, RFID reader.. whatever) to know how to treat those bytes.
Hope this helps.
Use Convert.ToBase64String()
method. This method convert byte array into Base64 string.
EDIT:
@Muhammad Ashraf : problem is not the byte DATA , problem is to the thread handling.
Yes It is cross-thread issue. You may use Invoke method.
private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1);
byte DATA = Convert.ToByte(serialPort1.ReadByte());
String data=Convert.ToString(DATA);
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new Action(() => { textBox1.Text = data; }));
}
}
精彩评论