【发布时间】:2014-01-29 04:44:50
【问题描述】:
我是 c# 的新手,我知道这个话题之前已经解决了,我尝试了一些解决方案大约 3 天,但没有一个有效,你能帮帮我吗?
我的问题是:我有一个班级Form1 和一个班级connection。 connection 类处理与串行端口的连接和通信。每次connection 类接收到一些信息时,OnSerialDataReceived - Eventhandler 就会被触发,并且信息字符串会保存在 received_data 中。
现在我想更新 Form1 中名为 tb_received 的文本框的文本,但我不知道如何从我的连接类获取到 tb_received 的连接。
请帮帮我,谢谢。
表格1:
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;
namespace mp6_Control_Rev1._0
{
public partial class Form1 : Form
{
Connection con;
public Form1()
{
InitializeComponent();
con= new Connection();
Disable();
bt_start_stop.Text = "Start";
rb_pump.Checked = true;
foreach (string port in con.Port())
{
dd_ports.Items.Add(port);
}
}
...............
}
Connection:#
using System;
using System.IO.Ports;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
namespace mp6_Control_Rev1._0
{
public class Connection : Form
{
public string[] ports;
public string received_data;
public int data_received_flag = 0; //Setzen durch Eventhandler
SerialPort serialPort1;
public String[] Port()
{
ports = SerialPort.GetPortNames();
return ports;
}
public bool check_port(string entry)
{
if (entry.Equals("avaible Ports"))
{
MessageBox.Show("Please choose an avaible Port");
return false;
}
else
{
return true;
}
}
public void new_DataReceived()
{
serialPort1.DataReceived += new SerialDataReceivedEventHandler(OnSerialDataReceived);
}
public void OnSerialDataReceived(object sender, SerialDataReceivedEventArgs args)
{
MessageBox.Show("Serialdatareceived");
received_data = serialPort1.ReadExisting();
data_received_flag = 1;
}
public void start_connection(string port)
{
try
{
serialPort1 = new SerialPort();
serialPort1.WriteTimeout = 500;
serialPort1.PortName = port;
serialPort1.BaudRate = 9600;
serialPort1.Parity = Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.Handshake = Handshake.None;
serialPort1.DtrEnable = true;
serialPort1.Open();
}
catch
{
MessageBox.Show("Connection failed, please try again.");
}
}
public void close_port()
{
serialPort1.Close();
}
public void send_string(string to_send)
{
if (serialPort1.IsOpen)
{
serialPort1.Write(to_send);
}
else
{
MessageBox.Show("Serial Port is closed, please connect !");
}
}
}
}
【问题讨论】: