关于读取串口

这两天做一个关于读取串口信息的程序,这个程序的两个关键点在于,读取串口中的信息,把信息写到当前光标所在的的位置。
读取串口信息的方法,这个容易,现循环获得当前有几个串口,添加到一个下拉框中
string [] ports=SerialPort.GetPortNames();
foreach(string port in ports)
{
 cmbComSelect.Items.Add(port);
}
把读到的信息写到当前光标所在,我第一个想到的是SendMessage
  int hwnd = WindowFromPoint(MousePosition.X, MousePosition.Y);//获取当前光标所在的窗口位置。
          
            if (hwnd != 0 )
            {

                SendMessage(hwnd, WM_GETTEXT, sb.Length, sb);//读取当前光标所在的信息
                sb.AppendLine(this.txtIn.Text);//在信息后面追加内容
                SendMessage(hwnd, WM_SETTEXT, 0, sb);//把信息传递到光标所在
            }
但这个方法有一个弊端,那就是WindowFromPoint(),限定于只能用于窗口,而且是一级窗体才行,比如说文本文档,在更具体的
文档里面就不行了,像Excel,word,IE里面都是不支持的。
因为根据方案是必须能在浏览器中支持的,so第一种方案就杯具了。
第二种方法是SendKeys,模拟键盘输入
 sb.Append(serialPort.ReadExisting());//获取串口信息
                int index = sb.ToString().Length;//计算有多少位需要传递
                if (index > 0)
                {
                    try
                    {
                        System.Windows.Forms.SendKeys.SendWait(sb.ToString(0, index));//传递内容
                    }
                    finally
                    { }
                }
这种方法也有一个弊端,那就是不支持IE浏览器,传递的内容和显示的内容不符,会出现数字的重复,但是在其他浏览器上测试没有问题。
可能是微软出的有冲突,呵呵。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
public partial class Form1 : Form { public Form1() { InitializeComponent(); } SerialPort port1 = new SerialPort(); string InputData = String.Empty; delegate void SetTextCallback(string text); private void Port_Select() {//获取机器中的串口地址 string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { comboBox1.Items.Add(port); } } private void Form1_Load_1(object sender, EventArgs e) { Port_Select(); this.comboBox1.SelectedIndex = 0; this.comboBox2.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { if (button1.Text == "关闭串口") //当要关闭串口的时候 { port1.DiscardOutBuffer(); port1.DiscardInBuffer(); port1.Close(); button1.Text = "打开串口"; label3.Text = "串口当前状况:未打开"; comboBox1.Enabled = true; comboBox2.Enabled = true; } else if (button1.Text == "打开串口") //当要打开串口的时候 { try { port1.PortName = comboBox1.SelectedItem.ToString(); port1.BaudRate = Convert.ToInt32(comboBox2.SelectedItem); port1.DataBits = 8; port1.RtsEnable = true; port1.Open(); port1.DiscardOutBuffer(); port1.DiscardInBuffer(); button1.Text = "关闭串口"; comboBox1.Enabled = false; comboBox2.Enabled = false; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + " 波特率:" + comboBox2.SelectedItem.ToString() + " 数据位:8 "; } catch { button1.Text = "打开串口"; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + "打开失败"; MessageBox.Show("该串口无法打开"); } } } 资源中部分代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

0x12

下载和转换脚本可私信我

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值