⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 form1.cs

📁 vs2005串口编程示例,好多例子,是学习串口编程方面不错的资料
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Diagnostics;
using System.IO.Ports;

namespace Ex13_02
{
    public partial class Form1 : Form
    {
        
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //打开串口
            serialPort1.PortName = "COM1";
            serialPort1.Open();
            button1.Enabled = false;
            button2.Enabled = true;
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] data = Convert.FromBase64String(serialPort1.ReadLine());
            string str = Encoding.Unicode.GetString(data);
            serialPort1.Close();
            if (str == "关机")
            {
                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                p.StandardInput.WriteLine("shutdown /s");
                p.StandardInput.WriteLine("exit");
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (button2.Text == "关闭计算机")
            {
                //发送关机命令数据
                byte[] data = Encoding.Unicode.GetBytes("关机");
                string str = Convert.ToBase64String(data);
                serialPort1.WriteLine(str);
                button2.Text = "取消关机";
            }
            else
            {
                button2.Text = "关闭计算机";
                button1.Enabled = true;
                button2.Enabled = false;
                //取消关机
                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                p.StandardInput.WriteLine("shutdown /a");
                p.StandardInput.WriteLine("exit");
            }
        }
        
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -