1. 程式人生 > >串列埠發指令控制工控機自動關機

串列埠發指令控制工控機自動關機


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;


namespace AutoShutDown
{
    public partial class Form1 : Form
    {
        SerialPort plc = new SerialPort("COM2", 9600, Parity.Odd, 8, StopBits.One);


        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            plc.DataReceived += new SerialDataReceivedEventHandler(plc_DataReceived);
            plc.Open();

        }

        private void plc_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] readBuffer = new byte[plc.ReadBufferSize];
            plc.Read(readBuffer, 0, readBuffer.Length);
            string readstr = Encoding.UTF8.GetString(readBuffer);


            if (readstr.Substring(0, 8) == "ShutDown")
            {
                var startInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardInput = true;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError = true;
                startInfo.CreateNoWindow = true;
                var myProcess = new System.Diagnostics.Process();
                myProcess.StartInfo = startInfo;
                myProcess.Start();
                myProcess.StandardInput.WriteLine("shutdown -s -t 0" );
            }
           
        }

    }
}