关闭对方计算机的应用程序

作者在 2011-11-02 00:26:48 发布以下内容
还是跟原先一样先摆好控件和控件对应的事件如下:
本实例是通过设置SerialPort的方法和属性来实现的下面简单介绍SerialPort的相关事件和属性:
SerialPort类的DataReceived 事件,DataReceived 事件为本实例的主要使用技术。DataReceived事件表示将处理 SerialPort 对象的数据接收事件的方法。串行接收事件可以由 SerialData 枚举中的任何项引起,是否引发此事件由操作系统决定,所以不一定会报告所有奇偶校验错误。启动Microsoft Visual Studio 2008新建一个项目,命名为关闭对方计算机程序(可以任意取),默认窗体为Form1,Form1窗体中,主要添加两个Button控件,分别用于打开通信串口(在text属性处修改)和关闭对方计算机(在text属性处修改)。
我就不废话了下面是整个程序的代码(可能不是很详细谅解):
private void button1_Click(object sender, EventArgs e)
        {
            //打开串口
            serialPort1.PortName = "COM1";
            serialPort1.Open();
            button1.Enabled = false;
            button2.Enabled = true;
        }   //数据接收事件,等待接收关机命令
        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");
            }
        }   //发送关机命令
        private void button2_Click(object sender, EventArgs e)
        {
            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");
            }
        }
搞定了
睡觉去:
哈哈
默认分类 | 阅读 695 次
文章评论,共0条
游客请输入验证码
文章分类