c# 显卡或主板自动开关机测试

  • Post author:
  • Post category:其他


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.IO;
using System.Diagnostics;
using System.Collections;
using System.Windows;

namespace AutoPowerOffTest
{
    public partial class Form1 : Form
    {
        public List<String> Confg;//存储配置
        public List<String> GetMacAddress;//存储Mac地址
        public int Complete_Count = 0;//完成开关机次数
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (ReadConfg("AutoPowerOffTest.config"))//读取配置
            {
                if (Local_Area_Network_ConnectState(Confg[1], @"admin", @"test"))//连接局域网
                {
                    if (GetSystemAllMacAddress(5))//读取Mac
                    {
                        if (Create_Log_Info(Confg[1] + @"\" + GetMacAddress[0] + @".log", Convert.ToInt32(Confg[0])))//创建日志
                        {
                            label1.Text = "已完成开关机:" + Complete_Count.ToString() + "次!!";
                            CloseFrom();
                            if (Complete_Count < Convert.ToInt32(Confg[0]))
                            {
                                Shutdown_Windows TestWindows = new Shutdown_Windows();
                                OpenFrom(TestWindows);
                            }
                            else
                            {
                                PASS Test_Result = new PASS();
                                OpenFrom(Test_Result);
                            }
                        }
                    }
                }
            }
        }


        //关闭已经打开的窗体方法
        private void CloseFrom()
        {
            foreach (Control item in this.panel1.Controls)
            {
                if (item is Form objControl)
                {

                    objControl.Close();
                    this.panel1.Controls.Remove(item);
                }

            }
        }
        //打开窗体方法
        private void OpenFrom(Form objFrm)
        {
            //将当前子窗体设置成非顶级控件
            objFrm.TopLevel = false;
            //设置窗体最大化
            objFrm.WindowState = FormWindowState.Maximized;
            //去掉窗体边框
            objFrm.FormBorderStyle = FormBorderStyle.None;
            //指定当前子窗体显示的容器
            objFrm.Parent = this.panel1;
            //显示窗体
            objFrm.Show();
        }
        public Boolean Create_Log_Info(String PathFileName, int Total_LoopCount)//创建日志信息
        {
            Boolean Flag = true;
            if (!Read_Comcomplete_Count(PathFileName))
            {
                Complete_Count = 1;
            }
            else
            {
                if(Complete_Count<Total_LoopCount)
                    Complete_Count++;
            }
            if (!Write_TestLoopCount_Record(PathFileName, Complete_Count))
                Flag = false;
            return Flag;
        }
        public Boolean Write_TestLoopCount_Record(String PathFileName,int count)//写已完成测试次数记录
        {
            Boolean Flag = true;
            FileStream fs = new FileStream(PathFileName,FileMode.Append|FileMode.Create,FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            try
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ff")+"--"+count.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"系统提醒",MessageBoxButtons.OK,MessageBoxIcon.Error);
                Flag = false;
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
            return Flag;
        }
        public Boolean Read_Comcomplete_Count(String PathFileName)//读取完成次数
        {
            Boolean Flag = true;
            if (File.Exists(PathFileName))
            {
                FileStream fs = new FileStream(PathFileName,FileMode.Open,FileAccess.Read);
                StreamReader sr = new StreamReader(fs,Encoding.Default);
                try
                {
                    String Temp = String.Empty;
                    while ((Temp = sr.ReadLine()) != null)
                    {
                        String[] Array_Str = Temp.Split(new String[] {"--"},StringSplitOptions.RemoveEmptyEntries);
                        if (Array_Str.Length >= 2)
                            Complete_Count = Convert.ToInt32(Array_Str[1]);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message,"系统提醒",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    Flag = false;
                }
                finally
                {
                    sr.Close();
                    fs.Close();
                }
            }
            else
            {
                Flag = false;
            }
            return Flag;
        }
        public Boolean GetSystemAllMacAddress(int num)//读取Mac_Address
        {
            Boolean Flag = false;
            try
            {
                NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();//读取网卡信息
                GetMacAddress = new List<string>();
                foreach (NetworkInterface adapter in adapters)
                {
                    if (adapter.GetPhysicalAddress().ToString() != " " && adapter.GetPhysicalAddress().ToString() != String.Empty)
                        GetMacAddress.Add(adapter.GetPhysicalAddress().ToString());
                }
                if (GetMacAddress.Count < num)
                {
                    for (int n = GetMacAddress.Count; n < num; n++)
                        GetMacAddress.Add(@"N\A         ");
                }
                Flag = true;
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex);
                Console.ResetColor();
                Flag = false;
            }

            return Flag;
        }
    public Boolean ReadConfg(String FileName)//读取配置信息
        {
            Boolean Flag = true;
            if (File.Exists(FileName))
            {
                Confg = new List<string>();
                FileStream fs = new FileStream(FileName,FileMode.Open,FileAccess.Read);
                StreamReader sr = new StreamReader(fs,Encoding.Default);
                try
                {
                    String Temp = String.Empty;
                    while ((Temp = sr.ReadLine()) != null)
                    {
                        String[] Array_Str = Temp.Split(new String[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                        if (Array_Str.Length >= 2)
                        {
                            Confg.Add(Array_Str[1].Trim());
                        }
                    }
                }
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message,"系统提醒",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    Flag = false;
                }
                finally
                {
                    sr.Close();
                    fs.Close();
                }
            }
            else
            {
                MessageBox.Show("No File "+FileName+" Found!!");
                System.Environment.Exit(1);
            }
            return Flag;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(1);
        }


        public Boolean Local_Area_Network_ConnectState(String Path, String UserName, String Password)//局域网连接
        {
            Boolean Flag = true;
            if (!Directory.Exists(Path))
            {
                Process proc = new Process();
                try
                {
                    proc.StartInfo.FileName = "cmd.exe";
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.RedirectStandardInput = true;
                    proc.StartInfo.RedirectStandardOutput = true;
                    proc.StartInfo.RedirectStandardError = true;
                    proc.StartInfo.CreateNoWindow = true;
                    proc.Start();
                    String dosLine = "net use " + Path + " " + Password + " /user:" + UserName;
                    proc.StandardInput.WriteLine(dosLine);
                    proc.StandardInput.WriteLine("exit");
                    while (!proc.HasExited)
                    {
                        proc.WaitForExit(1000);
                    }
                    string errormsg = proc.StandardError.ReadToEnd();
                    proc.StandardError.Close();
                    if (string.IsNullOrEmpty(errormsg))
                    {
                        Flag = true;
                    }
                    else
                    {
                        //throw new Exception(errormsg);
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(errormsg);
                        Console.ResetColor();
                        Flag = false;
                    }
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex.Message);
                    Console.ResetColor();
                    Flag = false;
                }
                finally
                {
                    proc.Close();
                    proc.Dispose();
                }
            } 
            return Flag;
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace AutoPowerOffTest
{
    public partial class Shutdown_Windows : Form
    {
        public int Count_Down = 5;//倒计时5秒
        public Shutdown_Windows()
        {
            InitializeComponent();
        }

        private void Shutdown_Windows_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            label1.ForeColor = Color.Red;
            label1.Text = "倒计时:"+Count_Down.ToString()+@"秒,执行 >>POWER OFF<<!!";
            if (Count_Down != 0)
                Count_Down--;
            else
            {
                Reboot();
                timer1.Enabled = false;
            }
        }

        public void Reboot()
        {
            Process p = new Process();//实例化一个独立进程
            p.StartInfo.FileName = "cmd.exe";//进程打开的文件为Cmd
            p.StartInfo.UseShellExecute = false;//是否启动系统外壳选否
            p.StartInfo.RedirectStandardInput = true;//这是是否从StandardInput输入
            p.StartInfo.CreateNoWindow = true;//这里是启动程序是否显示窗体
            p.Start();//启动
            p.StandardInput.WriteLine("shutdown -r -t 0");//运行关机命令shutdown (-s)是关机 (-t)是延迟的时间 这里用秒计算 10就是10秒后关机
            p.StandardInput.WriteLine("exit");//退出cmd 
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoPowerOffTest
{
    public partial class PASS : Form
    {
        public int i = 0;
        public PASS()
        {
            InitializeComponent();
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (i == 0)
            {
                label1.ForeColor = Color.Black;
                i = 1;
            }
            else if (i == 1)
            {
                label1.ForeColor = Color.LimeGreen;
                i = 0;
            }
        }
    }
}



版权声明:本文为u013934107原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。