一、创建一个Winform窗体,制作一个5s定时器
using System;
using System.Windows.Forms;
namespace 计时器
{
public partial class Form1 : Form
{
int count;
int time;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i < 6; i++)
{
comboBox1.Items.Add(i.ToString() + " 秒");
}
label3.Text = "";
}
//定时器事件
private void timer1_Tick(object sender, EventArgs e)
{
count++;//记当前秒
label3.Text = (time - count).ToString() + " 秒";//显示剩余时间
progressBar1.Value = count;//设置进度条进度
if(count==time)
{
timer1.Stop();//时间到,停止计时
System.Media.SystemSounds.Asterisk.Play();//提示音
MessageBox.Show("时间到!");//弹出提示框
}
}
//按钮 开始计时事件
private void button1_Click(object sender, EventArgs e)
{
string str=comboBox1.Text;//将下拉框内容添加到一个变量中
time = Convert.ToInt32(str.Substring(0,2));//得到设定定时值(整形)
progressBar1.Maximum = time;//进度条最大数值
timer1.Start();//开始计时
}
}
}
运行结果如下:
二、串口发数据
using System;
using System.Windows.Forms;
namespace 串口发数据
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
//窗口创建初始化函数
private void Form1_Load(object sender, EventArgs e)
{
string str;//用来临时存储大写的十六进制格式字符串
for(int i=0;i<256;i++)
{
//ToString("x")写法的目的:是为了将数字转换为16进制字符串,ToUpper是将字符串所有字符大写
str = i.ToString("x").ToUpper();
//comboBox1.Items.Add("0x"+(str.Length==1?"0"+str:str));
//如果是一位的(0xA),此时为了对齐,在数据前加一个字符"0"(0x0a)
if (str.Length == 1)
str = "0" + str;
comboBox1.Items.Add("0x" + str);//统一添加"0x"
}
comboBox1.Text = "0X00";//初始值
}
//按键单击事件
private void button1_Click(object sender, EventArgs e)
{
//存储当前下拉框的内容
string data = comboBox1.Text;
//把字符分开
string convertdata = data.Substring(2, 2);
//数据一个字节就够用了
byte[] buffer = new byte[1];
//将字符串转化为byte型变量(byte相当于单片机中unsigned )
buffer[0] = Convert.ToByte(convertdata, 16);
try
{
serialPort1.Open();
serialPort1.Write(buffer, 0, 1);
serialPort1.Close();
}
catch
{
//如果是写数据时出错,此时窗口状态为开,就应关闭串口,防止下次不能使用,串口是不能重复打开和关闭的。
if (serialPort1.IsOpen)
serialPort1.Close();
MessageBox.Show("端口错误", "错误");
}
}
}
}
运行结果为:
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace 开发串口助手
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
//打开端口
private void button1_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text,10);//十进制数据转换
serialPort1.Open();
button1.Enabled = false;//按钮“打开串口”不可用
button2.Enabled = true;//按钮“关闭串口”
}
catch
{
MessageBox.Show("端口错误,请检查串口", "错误");
}
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
}
//初始化
private void Form1_Load(object sender, EventArgs e)
{
for(int i=1;i<20;i++)
{
comboBox1.Items.Add("COM" + i.ToString());
}
comboBox1.Text = "COM1";//串口号默认值
comboBox2.Text = "4800";//波特率默认值
//需要手动添加串口的事件处理
serialPort1.DataReceived +=new SerialDataReceivedEventHandler(port_DataReceived);
}
//串口数据接收事件
private void port_DataReceived(object sender,SerialDataReceivedEventArgs e)
{
//如果接收模式为字符模式
if(!radioButton3.Checked)
{
string str = serialPort1.ReadExisting();//字符串方式读
textBox1.AppendText(str);//添加内容
}
else//如果接收模式为数值模式
{
byte data;
data = (byte)serialPort1.ReadByte();//强制类型转换,将int类型数据转换为byte类型数据
string str = Convert.ToString(data, 16).ToUpper();//转换为大写十六进制字符串
textBox1.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");//空位补"0"
}
}
//关闭端口
private void button2_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();//关闭串口
button1.Enabled = true;//按钮“打开串口” 可用
button2.Enabled = false;//按钮“关闭串口” 不可用
}
catch(Exception err)//一般情况下关闭串口不会出错,所以不需要加处理程序
{
}
}
//发送
private void button3_Click(object sender, EventArgs e)
{
byte[] Data = new byte[1];
//判断串口是否打开
if(serialPort1.IsOpen)
{
if(textBox2.Text!="")
{
//如果发送模式是字符模式
if (!radioButton1.Checked)
{
try
{
serialPort1.WriteLine(textBox2.Text);//写数据
}
catch (Exception err)
{
MessageBox.Show("串口数据写入错误", "错误");
serialPort1.Close();
button1.Enabled = true;//打开串口按钮可用
button2.Enabled = false;//关闭串口按钮不可用
}
}
else
{
//取余运算作用:防止用户输入的字符为奇数个。
for(int i=0;i<(textBox2.Text.Length-textBox2.Text.Length%2)/2;i++)
{
Data[0] = Convert.ToByte(textBox2.Text.Substring(i * 2, 2), 16);
serialPort1.Write(Data, 0, 1);//循环发送(如果输入字符为0A0BB,则只发送0A,0B)
}
//剩下一位单独处理
if(textBox2.Text.Length%2!=0)
{
//单独发送B(0B)
Data[0] = Convert.ToByte(textBox2.Text.Substring(textBox2.Text.Length - textBox2.Text.Length%2,textBox2.Text.Length%2),16);
serialPort1.Write(Data, 0, 1);//发送
}
}
}
}
}
//文本控件内容改变事件
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.ScrollToCaret();//将滚动条调至最下
}
}
}
串口连接后,运行结果为:
四、串口控制
/*串口控制下位机开关*/
using System;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
namespace 串口控制
{
public partial class Form1 : Form
{
//设备1
const byte DeviceOpen1 = 0x01;
const byte DeviceClose1 = 0x81;
//设备2
const byte DeviceOpen2 = 0x02;
const byte DeviceClose2 = 0x82;
//设备3
const byte DeviceOpen3 = 0x03;
const byte DeviceClose3 = 0x83;
//SerialPort Write Buffer
byte[] SerialPortDataBuffer = new byte[1];
public Form1()
{
InitializeComponent();
}
//打开串口
private void button2_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen)
{
try
{
serialPort1.Close();
}
catch { }
ovalShape1.FillColor = Color.Gray;
button2.Text = "打开串口";
}
else
{
try
{
serialPort1.PortName = comboBox1.Text;//端口号
serialPort1.Open();//打开端口
ovalShape1.FillColor = Color.Green;
button2.Text = "关闭串口";
}
catch
{
MessageBox.Show("串口打开失败", "错误");
}
}
}
//窗体初始化
private void Form1_Load(object sender, EventArgs e)
{
ovalShape1.FillColor = Color.Gray;
SearchAndAddSerialToComboBox(serialPort1, comboBox1);
}
//设备一开
private void button3_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceOpen1);
}
//设备一关
private void button4_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceClose1);
}
//设备二开
private void button5_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceOpen2);
}
//设备二关
private void button6_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceClose2);
}
//设备三开
private void button7_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceOpen3);
}
//设备三关
private void button8_Click(object sender, EventArgs e)
{
WriteByteToSerialPort(DeviceClose3);
}
//扫描并将扫描到的串口添加到下拉列表
private void button1_Click(object sender, EventArgs e)
{
SearchAndAddSerialToComboBox(serialPort1, comboBox1);
}
//扫描:将可用端口号添加到ComboBox
private void SearchAndAddSerialToComboBox(SerialPort MyPort, ComboBox MyBox)
{
string Buffer;//缓存
MyBox.Items.Clear();//清空ComboBox内容
for (int i = 1; i < 20; i++)
{
try
{
Buffer = "COM" + i.ToString();
MyPort.PortName = Buffer;
MyPort.Open();
MyBox.Items.Add(Buffer);//添加到下拉列表
MyPort.Close();
}
catch
{
}
}
}
//把数据写入串口
private void WriteByteToSerialPort(byte data)
{
byte[] Buffer = new byte[2] { 0x00, data };
if (serialPort1.IsOpen)
{
try
{
serialPort1.Write(Buffer, 0, 2);//写数据
}
catch
{
MessageBox.Show("串口数据发送出错,请检查", "错误");
}
}
}
}
}
首先打开电脑设备管理器,先查看一下电脑上有几个串口:
运行结果为:
五、图形化按钮设计