完成上位機控制臺串口后,接下來想用C#做一個Windows 窗口版的串口。上位機編程不是很熟練,每天學一點做一點。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace UartApp2
{public partial class Form1 : Form{public Form1(){InitializeComponent();InitializeForm();}private void InitializeForm(){// 設置窗體屬性this.Text = "串口通信工具 - COM8 @ 9600 bps";this.Size = new Size(800, 600);//this.BackColor = Color.AliceBlue;///Color.FromArgb(45, 45, 48);this.BackColor = Color.FromArgb(45,45,48);this.ForeColor = Color.White;this.FormClosing += MainForm_FormClosing;//這行代碼在 C# Windows 窗體應用程序中扮演著重要角色,用于處理窗體關閉前的操作。// this.FormClosing+=// 創建控件var titleLabel = new Label{Text = "串口通信工具",Font = new Font("Segoe UI", 18, FontStyle.Bold),ForeColor = Color.LightSkyBlue,AutoSize = true,Location = new Point(20, 20)};var configLabel = new Label{Text = "配置: COM8, 9600 bps, 8N1",Font = new Font("Segoe UI", 10),AutoSize = true,Location = new Point(20, 60)};var statusLabel = new Label{Text = "狀態: 未啟動",Font = new Font("Segoe UI", 10),AutoSize = true,Location = new Point(20, 90),ForeColor = Color.LightCoral};var sendButton = new Button{Text = "啟動發送",Font = new Font("Segoe UI", 10),Size = new Size(120, 40),Location = new Point(20, 130),BackColor = Color.FromArgb(0, 122, 204),FlatStyle = FlatStyle.Flat};// 添加到窗體this.Controls.Add(titleLabel);this.Controls.Add(configLabel);this.Controls.Add(statusLabel);this.Controls.Add(sendButton);}private void MainForm_FormClosing(object sender, FormClosingEventArgs e){if (MessageBox.Show("確定要退出嗎?", "確認",MessageBoxButtons.YesNo) == DialogResult.No){e.Cancel = true; // 取消關閉}}private void textBox1_TextChanged(object sender, EventArgs e){}}
}