Public static stringA ()
{
.
Port. The Open ();
Port. The method DataReceived +=Port_DataReceived;
return a;//here wants to make a the value of the company's
}
Private static void Port_DataReceived (object sender, SerialDataReceivedEventArgs e)
{
Byte [] portdata=https://bbs.csdn.net/topics/new byte [10].
Port. Read (portdata, 0, 10);
A=Encoding. UTF8. Get string (portdata);
}
CodePudding user response:
Private SerialPort SerialPort=new SerialPort ();Private StringBuilder builder=new StringBuilder ();
//private StringBuilder bs=new StringBuilder ();//used to store a complete information;
Boolean ope=false;
Public _click ()
{
InitializeComponent ();
Control. CheckForIllegalCrossThreadCalls=false;
}
Private void Form1_Load (object sender, EventArgs e)
{
String [] names=SerialPort. GetPortNames ();
If (names==null)
{
MessageBox. Show (" no available serial port ", "prompt");
}
The else
{
The foreach (string STR in names)
{
ToolStripComboBox2_Potrs. Items. The Add (STR);
}
}
ToolStripComboBox1_Rate. Text="9600";
ToolStripComboBox1_Rate. Items. The Add (" 4800 ");
ToolStripComboBox1_Rate. Items. The Add (" 9600 ");
//add event registration
Serialport. Method DataReceived +=new SerialDataReceivedEventHandler (serialPort_DataRecived);
}
Void serialPort_DataRecived (object sender, SerialDataReceivedEventArgs e)
{
Thread.sleep (500);
Builder. The Clear ();//remove the contents of the string constructor
String STR="";
Int n=serialport. BytesToRead;//record first, avoid losing
Label3. Text=n.T oString ();
Byte [] buf=new byte [n].
Serialport. Read (buf, 0, n);//read buffer data
This. Invoke ((EventHandler) (delegate
{
If (checkBox1_Hex. Checked)
{
Foreach (byte b in buf)
{
Builder. Append (b.T oString (" X2 ") + "");
}
}
The else
{
//direct rule as ASCII output
Builder. Append (Encoding. The ASCII. Get string (buf));
//bs. Append (Encoding. The ASCII. Get string (buf));
}
//append text
This. TextBox1_ReciMes. AppendText (builder. The ToString ());
//create a new thread
//;
Thread t=new Thread (new ParameterizedThreadStart (Options));
Console. WriteLine (builder. The ToString ());
T.S tart (builder. The ToString ());
}));
}
CodePudding user response:
A serial port is through asynchronous receive data, you can entrust the data inside the receiving method using program the main threadCodePudding user response:
Microsoft with events to you, of course, you can also use events to the outside,