我在代码中添加了它:
namespace uartToCs_version_2._0
{
public partial class formMain : Form
{
==> public static SerialPort serial = new SerialPort();
但是我没有使用“设计”选项卡,所以我应该如何处理事件(使用当前设置,我也可以其他形式使用它,这是否仍然可能)? My design file
答案 0 :(得分:1)
You can register the events either in any method like Load() or in the constructor. I used the constructor below. You can't register event until all the needed properties are setup. I did not show the setup code.
public partial class Form1 : Form
{
public static SerialPort serial = new SerialPort();
public Form1()
{
InitializeComponent();
serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
}
private void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
}
}
答案 1 :(得分:1)
public Form1()
{
InitializeComponent();
//add DataReceived event of serial
Form1.serial.DataReceived += serial_DataReceived;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
//remove DataReceived event of serial
Form1.serial.DataReceived -= serial_DataReceived;
}
void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//process data here
}