我是C語言的新手,正在撰寫一個從串口讀取資料的程式。我習慣于用C語言寫作,但不得不承認,我對面向物件的語言沒有什么經驗。我想讓一段代碼在不被呼叫的情況下運行以打開一個串口,也就是說,它將像在C語言中的int main()中一樣運行。我有下面的代碼來嘗試解決我的問題。
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
使用System.Threading.Tasks;
使用System.IO.Ports;
namespaceNav_Monitor
{
public partial class MainForm : Form
{
public MainForm(/span>)
{
InitializeComponent()。
}
private void t_tick(objectsender, EventArgs e)。
{
textBox1.Text = Environment.NewLine;
textBox1.Text = DateTime.Now.ToString("hh:mm:ss tt" )。
}
串行埠 serialPort;
private void openSerialPort(object sender, EventArgs e)。
{
serialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.1) 。
serialPort.Handshake = Handshake.None。
}
}
}
如果我把代碼移到openSerialPort方法之外,那么我就會得到一個錯誤'the name "serialPort" does not exist in the current context'.
。 serialPort = new SerialPort("COM1"/span>, 19200, parity. None, 8, StopBits.One)。)
serialPort.Handshake = Handshake.None。
private void openSerialPort(>object sender, EventArgs e)。
{
}
那么我是否需要類似于C語言中main()的東西來自動運行代碼?我似乎不應該把代碼放在我的program.cs檔案中,而這似乎是一個類似的地方。我很迷茫!
uj5u.com熱心網友回復:
最類似的方法其實是在Program.cs里面。Main()是C#應用程式的入門點。然而,您可以考慮在頁面加載后或在建構式中啟動任何后臺作業,如果該作業是非阻塞性的并且可以在后臺運行。
我看到您正在 Windows 表單中作業,其中 Form.Load 事件可能是打開串行埠的好地方。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/313118.html
標籤:
