namespace SerialPort
{
public partial class Form3 : Form
{
delegate void UpdateTextEventHandler(string text); //委托,此为重点
public static readonly string connStr = AppHelper.GetConfigValue("SqliteStr");
public Form3()
{
InitializeComponent();
}
#region 窗体加载
private void Form3_Load(object sender, EventArgs e)
{
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.Open();
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
//txtReceive.Text = "1.25";
}
#endregion
#region 关闭窗体
private void btnClose_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen) { serialPort1.Close(); }
this.Close();
}
#endregion
#region 委托侦测
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string SDateTemp = this.serialPort1.ReadExisting();
if (!string.IsNullOrEmpty(SDateTemp))
{
SDateTemp = GetValue(SDateTemp, "GS", "kg").Trim(); //多少kg
}
this.Invoke(new UpdateTextEventHandler(UpdateTextBox), new string[] { SDateTemp });
}
private void UpdateTextBox(string text)
{
if (!string.IsNullOrEmpty(text))
{
txtReceive.Text = text;
}
}
#endregion
#region 获得字符串中开始和结束字符串之间的值
///
/// 获得字符串中开始和结束字符串之间的值
///
/// 字符串
/// 开始
/// 结束
///
public static string GetValue(string str, string s, string e)
{
Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(str).Value;
}
#endregion
}
}
有form1与form2两个窗体,启动form1 form1的button.click打开form2,在form2的textbox中输入文本在form1的textbox中同步显示
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Demo0003
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 fr2 = new Form2();
//即便你不用实时监控但你也要知道你委托给谁去办事了吧
//他会带来你需要的信息 然后你该干吗就干吗
fr2.fangfa += fuzhi;
fr2.Show();
}
public void fuzhi(string str)
{
this.textBox1.Text = str;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Demo0003
{
public delegate void delegateclass(string str);
public partial class Form2 : Form
{
//哦明白了
public event delegateclass fangfa;
public Form2()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
string str = this.textBox1.Text;
Form1 f1 = new Form1();
//我变化啦
fangfa(str);
//多窗体间为多线程传递只能使用委托亲
}
}
}