简体   繁体   中英

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. When I debug the program and send string "S" from my Arduino, the console application simply closes without a printout.

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. Furthermore I am in need of help regarding Visual Studio 2013, I am unfamiliar with C# and the application. My project is a console application, is it possible to create a windows forms application using the same code? 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);
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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