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

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

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"); } }

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