.net趣味开发通过串口关闭对方计算机

2025-04-02 16:46:13

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

.net趣味开发通过串口关闭对方计算机

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

.net趣味开发通过串口关闭对方计算机

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

.net趣味开发通过串口关闭对方计算机

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

.net趣味开发通过串口关闭对方计算机

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

.net趣味开发通过串口关闭对方计算机

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

.net趣味开发通过串口关闭对方计算机

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢