繁体   English   中英

如何用C#制作Windows窗体应用程序以接收来自串行端口的数据

[英]How to make a windows forms application in C# that can receive data from a serial port

我有这个(工作)代码,用于从串行端口接收数据并将其显示在c#的控制台应用程序中。

#region Namespace Inclusions
using System;
using System.IO.Ports;
using System.Windows.Forms;
#endregion

namespace SerialPortExample
{
  class SerialPortProgram
  {
    // Create the serial port with basic settings
    private SerialPort port = new SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One);

    [STAThread]
    static void Main(string[] args)
    { 
      // Instatiate this class
      new SerialPortProgram();
    }

    private SerialPortProgram()
    {
      Console.WriteLine("Incoming Data:");

      // Attach a method to be called when there
      // is data waiting in the port's buffer
      port.DataReceived += new 
        SerialDataReceivedEventHandler(port_DataReceived);

      // Begin communications
      port.Open();

      // Enter an application loop to keep this thread alive
      Application.Run();
    }

    private void port_DataReceived(object sender,
      SerialDataReceivedEventArgs e)
    {
  // Show all the incoming data in the port's buffer
  Console.WriteLine(port.ReadExisting());
    }
  }
}

但是,如何将这段代码转移到Windows窗体应用程序上呢?

我知道这是一个模糊的问题,但是如果可以的话,请为这个应用程序提供一些示例代码。

如果添加以下行来替换Application.Run语句,则应该可以使用了。 (删除原来的port.DataReceived行)

var frm = new Form { Height = 200, Width = 200 };
var txt = new TextBox {Dock = DockStyle.Fill, Multiline=true };
frm.Controls.Add(txt);
port.DataReceived += (sender, args) => { 
        if (txt.InvokeRequired)
        {
            txt.Invoke(new MethodInvoker(() => { 
                txt.Text += port.ReadExisting(); 
                }));
        } 
        else  
        {
           txt.Text += port.ReadExisting(); 
        }
   };
Application.Run( frm);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM