简体   繁体   English

使用Visual Studio 2013和Arduino串行/ COM端口使用C#关闭Windows 7

[英]Shutdown Windows 7 with C# using Visual Studio 2013 and Arduino serial/COM port

I am trying to create a program that will shutdown my system when a specific string or character is sent from my Arduino. 我正在尝试创建一个程序,当从Arduino发送特定的字符串或字符时,该程序将关闭系统。 When I debug the program and send string "S" from my Arduino, the console application simply closes without a printout. 当我调试程序并从Arduino发送字符串“ S”时,控制台应用程序仅关闭而没有打印输出。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Diagnostics;

namespace Arduino_Test
{
class Program
    {
    static void Main(string[] args)
        {
        SerialPort myport = new SerialPort();
        myport.BaudRate = 9600;
        myport.PortName = "COM5";
        myport.Open();

            string data_rx = myport.ReadLine();
            string s = "S";
            if(data_rx == s)
            {
               Console.WriteLine(data_rx);
               var psi = new ProcessStartInfo("shutdown", "/s /f /t 0");
               psi.CreateNoWindow = true;
               psi.UseShellExecute = false;
               Process.Start(psi);
            }
        }
    }
}

I suspect something is wrong within the if statement. 我怀疑if语句中有问题。 Furthermore I am in need of help regarding Visual Studio 2013, I am unfamiliar with C# and the application. 此外,我需要有关Visual Studio 2013的帮助,我不熟悉C#和应用程序。 My project is a console application, is it possible to create a windows forms application using the same code? 我的项目是控制台应用程序,是否可以使用相同的代码创建Windows窗体应用程序? I am under experienced in this field and your patience is appreciated. 我在这方面经验不足,感谢您的耐心配合。

You will want to define some new terminal state, but lets pretend that it should run forever. 您将要定义一些新的终端状态,但请假装它应该永远运行。 If that is the case, simply put your read code in a loop. 如果是这种情况,只需将读取的代码放入循环中即可。

while(true) {
        string data_rx = myport.ReadLine();
        string s = "S";
        if(data_rx == s)
        {
           Console.WriteLine(data_rx);
           var psi = new ProcessStartInfo("shutdown", "/s /f /t 0");
           psi.CreateNoWindow = true;
           psi.UseShellExecute = false;
           Process.Start(psi);
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM