WinCE SerialPort

直接上代码

窗体加载
1 privatevoid Form1_Load(object sender, EventArgs e)
2 {
3 serialPort1.PortName ="COM3";
4 serialPort1.BaudRate =9600;
5 serialPort1.DataBits =8;
6 serialPort1.Open();
7 if (serialPort1.IsOpen)
8 {
9 serialPort1.PortName+"端口已打开"
10 }
11 else
12 {
13 serialPort1.PortName+"端口打开 失败"
14 }
15 }
SerialPort DataReceived
privatevoid serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
System.Threading.Thread.Sleep(
120);
int bytes = serialPort1.BytesToRead;
byte[] buffer =newbyte[bytes];
if (bytes ==0)
{
return; }
serialPort1.Read(buffer,
0, bytes);
RfidLoad(ByteToStr(buffer));
}
委托
publicvoid RfidLoad(string msg)
{
this.Invoke(new EventHandler(delegate
{
try
{
if (!string.IsNullOrEmpty(msg))
{
if (!listBox1.Items.Contains(msg))
{
listBox1.Items.Add(msg);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}));
}
转换
publicstring ByteToStr(byte[] value)
{
string item =string.Empty;
if (((value.Length >8) && (value.Length >= ((((value[4] >>3) +1) *2) +4))) && ((((value[2] &0x7f) ==0x10) || ((value[2] &0x7f) ==0x11)) && (value[3] !=1)))
{
int num = ((value[4] >>3) +1) *2;
bool flag =false;
for (int i =0; i < num; i++)
{
if (!flag)
{
if (value[4+ i] ==0xff)
{
flag
=true;
}
else
{
item
+= Convert.ToString((int)(value[4+ i] >>4), 0x10) + Convert.ToString((int)(value[4+ i] &15), 0x10);
}
}
else
{
flag
=false;
item
+= Convert.ToString((int)(value[4+ i] >>4), 0x10) + Convert.ToString((int)(value[4+ i] &15), 0x10);
}
}
}
if (!string.IsNullOrEmpty(item))
{
return item.ToUpper().Substring(4, 24);
}
return item;
}


posted @ 2011-06-11 20:29  微米大大  阅读(698)  评论(0编辑  收藏  举报