您的位置:首页 > 编程语言 > C#

C# 简单的串口读取

2013-04-21 15:20 363 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace ComTest
{
public partial class ComTest : Form
{
SerialPort comport = new SerialPort();
public ComTest()
{
InitializeComponent();
}

private void ComTest_Load(object sender, EventArgs e)
{
FindPort();
}

private void bt_c_Click(object sender, EventArgs e)
{

if (comport.IsOpen == false)
{
comport.PortName = com.SelectedItem.ToString();
comport.BaudRate = 9600;
comport.Parity = Parity.None;
comport.DataBits = 8;
comport.StopBits = StopBits.One;
comport.Handshake = Handshake.None;
try
{
comport.DataReceived += new SerialDataReceivedEventHandler(this.Data_Received);
comport.Open();
bt_c.Text = "关闭";

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
comport.Close();
bt_c.Text = "打开";
}
}

private void Data_Received(object sender,SerialDataReceivedEventArgs e)
{
this.text.Text = comport.ReadLine();
}

protected override void WndProc(ref Message m)//监视Windows消息
{
const int WM_DEVICECHANGE = 0x219;
//const int WM_DEVICEARRVIAL = 0x8000;//如果m.Msg的值为0x8000那么表示有U盘插入
//const int WM_DEVICEMOVECOMPLETE = 0x8004;//表示有U盘移除
if(m.Msg==WM_DEVICECHANGE)
{
FindPort();
}
base.WndProc(ref m); //将系统消息传递自父类的WndProc
}

public void FindPort()
{
this.com.Items.Clear();
string[] portlist = SerialPort.GetPortNames();
this.com.Items.AddRange(portlist);
com.SelectedIndex = com.Items.Count > 0 ? 0 : -1;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: