.net趣味开发通过串口关闭对方计算机
1、新建一个项目,命名为通过串口关闭对方计算机,默认窗体为Form1。如图

2、在Form1窗体中扯矿,主要添加两个Button控件,分别命名为打开通信串口和关闭对方计算机,分别用于打开通信串口和关闭对方计算机。

3、向窗体中添加serialPort控件,这个步骤是关键。如图所示。

4、开始添加程序,双击打开通信串口按钮,这里以com1串口做演示。
//打开串口代码
serialPort1.PortName = "COM1";
serialPort1.Open();
button1.Enabled = false;
button2.Enabled = true;

5、找到serialPort的DataReceived方法点击去:
//数据接收事件,接收关机命令
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");
}
}

6、双击关闭对方计算机按钮,这里以com1串口做演示。
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");
}

7、运行程序,测试既得到结果。