有如下一段代码,我该如何在其他的方法里调用receivedString这个函数
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolBar;
namespace xiaoniu
{
public partial class Form1 : Form
{ // 声明一个byte数组,用于存储接收到的数据
byte[] receiveBuffer = new byte[10];
// 声明一个变量,用于记录已经接收的数据字节数
int receivedBytes = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) // 主窗口
{
//获取电脑当前可用串口并添加到选项列表中
ComboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
SerialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
}
private void Button1_Click(object sender, EventArgs e) //点击打开串口
{
try
{
if (SerialPort1.IsOpen)
{
SerialPort1.Close();
Button1.Text = "点击打开串口";
}
else
{
SerialPort1.PortName = ComboBox1.Text;
SerialPort1.Open();
Button1.Text = "点击关闭串口";
}
}
catch (Exception ex)
{
//捕获可能发生的异常并进行处理
//捕获到异常,创建一个新的对象,之前的不可以再用
SerialPort1 = new System.IO.Ports.SerialPort();
//刷新COM口选项
ComboBox1.Items.Clear();
ComboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
Button1.Text = "打开串口";
Button1.BackColor = Color.ForestGreen;
MessageBox.Show(ex.Message);
}
}
private void Button4_Click(object sender, EventArgs e) //全选所有功能
{
RadioButton5.Checked = true;
checkBox1.Checked = true;
checkBox2.Checked = true;
}
private void RadioButton5_CheckedChanged(object sender, EventArgs e) //控制器类
{
}
private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) //串口类
{ // 检查是否允许跨线程调用控件,这里为了简化代码直接禁用了该功能
CheckForIllegalCrossThreadCalls = false;
// 读取所有可用字节数
int bytesToRead = SerialPort1.BytesToRead;
// 如果缓冲区大小不足以存储所有的字节,则扩展缓冲区
if (receivedBytes + bytesToRead > receiveBuffer.Length)
{
Array.Resize(ref receiveBuffer, receivedBytes + bytesToRead);
}
// 将所有可用字节读取到缓冲区中
SerialPort1.Read(receiveBuffer, receivedBytes, bytesToRead);
// 更新已经接收的字节数
receivedBytes += bytesToRead;
// 如果已经接收到了所有数据,则进行处理
if (receivedBytes == receiveBuffer.Length)
{
// 将接收到的数据转换为十六进制字符串
string receivedString = BitConverter.ToString(receiveBuffer).Replace("-", "");
// 将接收到的数据显示到文本框中
//textBox1.AppendText(receivedString + " ");
// 将接收到的数据写入到文件中
using (StreamWriter sw = new StreamWriter(@"C:\Users\g'x'r\Desktop\jieshou.txt", true))
{
sw.Write(receivedString + " ");
}
// 清空接收缓冲区和已接收的字节数
receivedBytes = 0;
Array.Clear(receiveBuffer, 0, receiveBuffer.Length);
}
}
}
}