答案 0 :(得分:2)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static SerialPort serialPort1;
public class ThreadWork
{
public static void DoWork()
{
serialPort1 = new SerialPort();
//stuff
}
}
private void Form1_Load(object sender, EventArgs e)
{
ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
Thread myThread = new Thread(myThreadDelegate);
myThread.Start();
}
private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string response = serialPort1.ReadLine();
this.BeginInvoke(new MethodInvoker(() => textBox1.AppendText(response + "\r\n")));
}
}
你真的不需要让DoWork()静态。
答案 1 :(得分:2)
这将编译好。当然,您必须提供thePort
个真实设置。
namespace csWinFormsTest
{
public partial class Form1 : Form
{
static System.IO.Ports.SerialPort thePort;
public Form1()
{
InitializeComponent();
thePort = new System.IO.Ports.SerialPort("COM1");
}
static void fcn()
{
MessageBox.Show(thePort.PortName);
}
}
}