VS上利用C#实现一个简单的串口程序记录

时间:2021-12-16 16:10:28

一、背景

  工作上需要利用串口往下位机写入数据,VC太老,正好借此机会来熟悉一直很想接触的VS之C#。

  感谢Tony托尼哥的串口通信代码,感谢梦真的C#的技术支持。

二、正文

  1、项目架构:(以我现有的知识认知来说)

    一共有3个文件:

    a、"Program.cs"保存的是主程序入口。

    b、"Form1.Designer.cs"图形控件的实现。

    c、"Form1.cs"里面实现的既是用户逻辑。

    典型代码结构如下:

最先运行文件"Program.cs"内的主程序
namespace TB528E4PSE_APP
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new VOUTCTRL());-----------------------|
} |
} |
} |
然后接着运行"Form1.cs" 文件内的"VOUTCTRL()".    |
namespace TB528E4PSE_APP |
{ |
public partial class VOUTCTRL : Form |
{ |
SerialPort serialPort; |
|
public VOUTCTRL() <---------------------------------------|
{
//IntializeComponent()函数在"Form1.Designer.cs"里实现,
       //功能是初始化图形界面
//在图形界面操作时,该代码会被VS自动更改
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
//获取串口
String[] serialPortArray = SerialPort.GetPortNames();
if (serialPortArray != null && serialPortArray.Length != )
{
//对串口进行排序
Array.Sort<String>(serialPortArray);
foreach (String port in serialPortArray)
{
//添加到combox的item
if (port != null && port.Length != )
comboBox_SPort.Items.Add(port);
}
}
//设置初始显示的值
comboBox_SPort.SelectedIndex = ;
serialPort = new SerialPort();
} private void button_SPort_Click(object sender, EventArgs e)
{
// 在图形界面编辑时,双击Button控件,该函数由VS自动生成
// 打开窗口
if (button_SPort.Text == "Open")
{
if (serialPort.IsOpen)
serialPort.Close();
try
{
setPort();
serialPort.Open();
button_SPort.Text = "Close";
}
catch (Exception ex)
{
MessageBox.Show("Uable to open this serial port!\n");
}
}
else
{
button_SPort.Text = "Open";
serialPort.Close();
}
} private void trackBar_VOUT1_Scroll(object sender, EventArgs e)
{
// 在图形界面编辑时,双击trackBar类控件,该函数由VS自动生成
// 拖动trackBar_VOUT1控件实现的逻辑
/* 一些代码逻辑,就不详细贴了。
...
setSerialVOUT(_Channel_1, _LV0);
...
*/
} private void trackBar_VOUT2_Scroll(object sender, EventArgs e)
{
// 在图形界面编辑时,双击trackBar类控件,该函数由VS自动生成
// 拖动trackBar_VOUT2控件实现的逻辑
/* 一些代码逻辑,就不详细贴了。
...
setSerialVOUT(_Channel_2, _LV0);
...
*/
} private void setPort() // 初始化串口
{
try
{
serialPort.PortName = (String)(comboBox_SPort.SelectedItem);
serialPort.BaudRate = ;
serialPort.DataBits = ;
serialPort.StopBits = StopBits.One;
serialPort.Parity = Parity.None;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
} private void setSerialVOUT(byte channel, byte level)
{
byte[] buf = new byte[]; // C#创建数组的方法
buf[] = channel;
buf[] = level;
buf[] = (byte)''; if (serialPort != null && serialPort.IsOpen)
{
serialPort.Write(buf,,); // 向串口写入数据
}
}
}
} 文件"Form1.Designer.cs"里包含的函数"InitializeComponent();"
namespace TB528E4PSE_APP
{
partial class VOUTCTRL
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows 窗体设计器生成的代码 /// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = \
          new System.ComponentModel.ComponentResourceManager(typeof(VOUTCTRL));
this.trackBar_VOUT2 = new System.Windows.Forms.TrackBar();
this.trackBar_VOUT1 = new System.Windows.Forms.TrackBar();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.textBox_VOUT1 = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox_VOUT2 = new System.Windows.Forms.TextBox();
this.comboBox_SPort = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.button_SPort = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)\
        (this.trackBar_VOUT2)).BeginInit();
((System.ComponentModel.ISupportInitialize)\
        (this.trackBar_VOUT1)).BeginInit();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// trackBar_VOUT2
//
this.trackBar_VOUT2.LargeChange = ;
this.trackBar_VOUT2.Location = new System.Drawing.Point(, );
this.trackBar_VOUT2.Maximum = ;
this.trackBar_VOUT2.Name = "trackBar_VOUT2";
this.trackBar_VOUT2.Size = new System.Drawing.Size(, );
this.trackBar_VOUT2.TabIndex = ;
this.trackBar_VOUT2.Scroll += new \
          System.EventHandler(this.trackBar_VOUT2_Scroll);
//
// trackBar_VOUT1
//
this.trackBar_VOUT1.BackColor = System.Drawing.SystemColors.Control;
this.trackBar_VOUT1.LargeChange = ;
this.trackBar_VOUT1.Location = new System.Drawing.Point(, );
this.trackBar_VOUT1.Maximum = ;
this.trackBar_VOUT1.Name = "trackBar_VOUT1";
this.trackBar_VOUT1.Size = new System.Drawing.Size(, );
this.trackBar_VOUT1.TabIndex = ;
this.trackBar_VOUT1.Scroll += new \
          System.EventHandler(this.trackBar_VOUT1_Scroll);
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)\
          ((System.Windows.Forms.AnchorStyles.Bottom | \
            System.Windows.Forms.AnchorStyles.Left)));
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.textBox_VOUT1);
this.groupBox1.Controls.Add(this.trackBar_VOUT1);
this.groupBox1.Location = new System.Drawing.Point(, );
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(, );
this.groupBox1.TabIndex = ;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "VOUT1";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(, );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(, );
this.label1.TabIndex = ;
this.label1.Text = "LEVEL";
//
// textBox_VOUT1
//
this.textBox_VOUT1.Location = new System.Drawing.Point(, );
this.textBox_VOUT1.Name = "textBox_VOUT1";
this.textBox_VOUT1.ReadOnly = true;
this.textBox_VOUT1.Size = new System.Drawing.Size(, );
this.textBox_VOUT1.TabIndex = ;
this.textBox_VOUT1.Text = "LV 0";
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)\
          ((System.Windows.Forms.AnchorStyles.Bottom | \
            System.Windows.Forms.AnchorStyles.Left)));
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.textBox_VOUT2);
this.groupBox2.Controls.Add(this.trackBar_VOUT2);
this.groupBox2.Location = new System.Drawing.Point(, );
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(, );
this.groupBox2.TabIndex = ;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "VOUT2";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(, );
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(, );
this.label2.TabIndex = ;
this.label2.Text = "LEVEL";
//
// textBox_VOUT2
//
this.textBox_VOUT2.Location = new System.Drawing.Point(, );
this.textBox_VOUT2.Name = "textBox_VOUT2";
this.textBox_VOUT2.ReadOnly = true;
this.textBox_VOUT2.Size = new System.Drawing.Size(, );
this.textBox_VOUT2.TabIndex = ;
this.textBox_VOUT2.Text = "LV 0";
//
// comboBox_SPort
//
this.comboBox_SPort.FormattingEnabled = true;
this.comboBox_SPort.Location = new System.Drawing.Point(, );
this.comboBox_SPort.Name = "comboBox_SPort";
this.comboBox_SPort.Size = new System.Drawing.Size(, );
this.comboBox_SPort.TabIndex = ;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(, );
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(, );
this.label3.TabIndex = ;
this.label3.Text = "SerialPort";
//
// button_SPort
//
this.button_SPort.Location = new \
          System.Drawing.Point(, );
this.button_SPort.Name = "button_SPort";
this.button_SPort.Size = new \
          System.Drawing.Size(, );
this.button_SPort.TabIndex = ;
this.button_SPort.Text = "Open";
this.button_SPort.UseVisualStyleBackColor = true;
this.button_SPort.Click += new \
          System.EventHandler(this.button_SPort_Click);
//
// VOUTCTRL
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(, );
this.Controls.Add(this.button_SPort);
this.Controls.Add(this.label3);
this.Controls.Add(this.comboBox_SPort);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.groupBox2);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "VOUTCTRL";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "TB528E4PSE";
((System.ComponentModel.ISupportInitialize)(this.trackBar_VOUT2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar_VOUT1)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout(); } #endregion private System.Windows.Forms.TrackBar trackBar_VOUT2;
private System.Windows.Forms.TrackBar trackBar_VOUT1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox_VOUT1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox_VOUT2;
private System.Windows.Forms.ComboBox comboBox_SPort;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button button_SPort; }
}

  至此,代码跟踪至此。

  2、更改窗体在屏幕首次出现的位置

    即当APP运行时,窗体会在电脑屏幕的哪个位置弹出。点击窗体->属性,

    找到“startposition”,如下图:

    VS上利用C#实现一个简单的串口程序记录

    注意以上图片包含的信息:Text选项,此处则可以表明窗体显示的信息。

  3,更改窗体显示的图标。

    即当APP运行时,窗体在Text旁边的图片,点击窗体->属性,

    找到“Icon”,如下图:

    VS上利用C#实现一个简单的串口程序记录

  4、如何发布程序:

    点击项目栏“生成”,点击“发布”选项即可发布程序了,如下图:

    VS上利用C#实现一个简单的串口程序记录

    生成的文件如下图:

     VS上利用C#实现一个简单的串口程序记录

    点击后缀名为".application"即可实现安装。

   5、发布安装后,程序在桌面显示的图标,以及支持的".NET frameworkXX.XX"设置。

    在项目右击,选择属性,会跳出窗体"项目名.csproj"文件,

    里面可进行相应设置,如下图:

    VS上利用C#实现一个简单的串口程序记录

三、参考链接

  Tony被参考的源代码github地址:

  https://github.com/TonySudo/SerialPortW    

  至此,记录完毕

记录时间:2016-8-26

记录地点:深圳WZ