我試圖從程序中製作一個C#,它是一個帶有四個按鈕的簡單框:左,右,上,下。那麼當一個按鈕被初始按下時(但不會放開),它會發送一個串行線。然後當按鈕被點擊時(用戶放開鼠標左鍵)我想發送另一個串行命令。如何在我的Windows Forms應用程序中使用串口?
問題是,每個void OnClick... (object sender, System.EventArgs e)
與其他人分開,並且串口「端口」在整個程序中不起作用。我在主要用於串行應用:
SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
port.Open();
我不想打開和關閉串口我想送點東西,因爲它可能太靠近在一起(在時間上),並且可能導致每次「串口在使用」問題和/或滯後於串口線的發送。
盡我所能地瘦下來。
代碼:
public class EAS_ControlForm : System.Windows.Forms.Form
{
private Button Up4;
private Button Down3;
private Button Left2;
private Button Right1;
public EAS_ControlForm()
{
Text = "Etch-a-Sketch Control";
Down3 = new Button();
Up4 = new Button();
Left2 = new Button();
Right1 = new Button();
Down3.Text = "Down";
Down3.Name = "Down3";
Down3.Size = new System.Drawing.Size (72, 30);
Down3.Location = new System.Drawing.Point ((ClientRectangle.Width - Down3.Size.Width)/2, ClientRectangle.Height - 10);
Controls.AddRange(new System.Windows.Forms.Control[] {this.Down3});
Down3.Click += new System.EventHandler(OnClickDown3);
Up4.Text = "Up";
///...button up4 stuff here like down 3 above.
Left2.Text = "Left";
///...button left2 stuff here like down 3 above.
Right1.Text = "Right";
///...button right1 stuff here like down 3 above.
}
static public void Main()
{
SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
port.Open();
Application.Run(new EAS_ControlForm());
}
void OnClickDown3 (object sender, System.EventArgs e)
{
port.Write("<3,100>");
}
void OnClickUp4 (object sender, System.EventArgs e)
{
port.Write("<4,100>"); //error here because of port initialization not in same code
}
void OnClickLeft2 (object sender, System.EventArgs e)
{
port.Write("<2,100>");
}
void OnClickRight1 (object sender, System.EventArgs e)
{
port.Write("<1,100>");
}
}
}
我覺得我有你的工作,但我不知道,因爲我不能使用膩子和我的應用程序在相同的,因爲:1.如果我有第一膩子,然後我的程序崩潰。 2.如果我先打開我的程序,然後膩子,膩子不會連接。 – Csharpz
Windows不允許多個進程同時打開串口。可以製作一個驅動程序來打開一個串行端口,然後通過兩個虛擬串行端口將其共享,但這有點複雜。 – rare
這就是我的想法。我沒有機器人連接到串口,所以我實際上可以測試它。只是想看看它是否發送命令。我現在用繪圖機器人試過了,它確實有用,所以謝謝! – Csharpz