using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using GcDevicePc.IniParam;
using System.IO;
using System.Runtime.InteropServices;
using GcDevicePc.ProThread;
using System.Security.Cryptography;
using System.Diagnostics;

namespace GcDevicePc
{
    //public delegate void EnableForm4ForHD(string  filename); 
 
    public delegate void invokeDelegate();
    public partial class MainBase : Form
    {    
        Point dwPoint;
        bool moveFlag;
       // bool draw_flag = false;

        ////主界面类
       CurveDisPlay curdisplay = new CurveDisPlay();
      //  Form4 curdisplay = new Form4();

        ////数据显示类
        DataState dockPanelSideLeft = new DataState();

       // Test uitest = new Test();

        //网络配置
        //ListViewTest f_netconfig = new ListViewTest();
        UserConfig appstartup = new UserConfig();

        //方法浏览窗口
     //   BrowseForm f_browsemethod = new BrowseForm();
        //MethodScan f_browsemethod = new MethodScan();       

        //批处理
        RunTables f_runtable = new RunTables();

        //辅助工具
        auxtool f_auxtool = new auxtool();

        //仪器配置
        InstrConfig f_showcfg = new InstrConfig();

        //数据查询
        WaveTotalForm queryprocess = new WaveTotalForm();

        //数据校准
        AdjustFrom dataadjust = new AdjustFrom();

        //历史图谱

        HistChartForm Historical_Atlas = new HistChartForm();
      
        //新建
        MethodNameInputForm m_methodNameInputForm = new MethodNameInputForm();

        //开启系统线程
       // Thread Bat_Run;    
        Thread Connect_Status;
        //Thread Data_Record;

        ushort GCstatus = 9;

        public TextBox textconent;
       // GcDataReq singlemodbus = new GcDataReq(globaldata.connection_ip, globaldata.datamodbusport);

        //HMI控制接口
        HMIControl hmiopt = new HMIControl(globaldata.connection_ip, globaldata.datamodbusport);

        //HMI数据获取接口
        GcDataTh mymodbus = new GcDataTh(globaldata.connection_ip, globaldata.datamodbusport);

        //本地数据保存接口
        ChannelDataSave mydatasave = new ChannelDataSave();
        //处理数据接口
        CKvocUpdata dataVOC = new CKvocUpdata();

        //状态改变信号
       // ManualResetEvent rsmre = new ManualResetEvent(false);
        ManualResetEvent datamre = new ManualResetEvent(false);
        ManualResetEvent conmre = new ManualResetEvent(false);

        bool inifilec = false;

        System.DateTime startTime, endTime;
        System.TimeSpan time;

        public MainBase()
        {
            //MainBase初始化
            InitializeComponent();      
            //运行环境初始化
            MainBase_InitAppConfig();
            dllInit();
            //标题初始化
            ManinBase_InitFormTitle();
            //菜单初始化
            MainBase_InitFromMenu();
            //开启线程
            
            Start_Thread();
            Start_ConnectStatusThread();
         
                     
            /////////////////////////////////////////////////
            //mydatasave.ChannelDataStart();         
            //mymodbus.HmiStatueStart();
            //mymodbus.ChannelDataStart();
     startTime = System.DateTime.Now;
          


        }

        private void dllInit() //组件初始化
        {
            //初始化路径
            CKVocAnalyzer.Config.Instance.ReadPath();
            //DLL初始化
            CKVocAnalyzer.VOCEntityConfig.Instance.vocinit();
            CKVocAnalyzer.Config.Instance.ReadAxisRange();
            LogOperate.LogInit.Instance.path = CKVocAnalyzer.GlobalCKV.FolderLog;
            LogOperate.LogInit.Instance.Init();
            CKVocAnalyzer.GlobalCKV.tcpservice.tcpStart(CKVocAnalyzer.GlobalCKV.hostadd,CKVocAnalyzer.GlobalCKV.tcpport);
            Trace.WriteLine("系统启动", "sys");


        }

        private void Start_ConnectStatusThread()
        {
            Connect_Status = new Thread(Monitor_Connect);
            Connect_Status.IsBackground = true;
            Connect_Status.Start();
        }

        /// <summary>
        /// HMI状态获取
        /// </summary>
        private void Monitor_Connect()
        {
            System.UInt16[] dest = new System.UInt16[9];
            int ret = 0 ;
            int LoseNum = 0;
            ushort status_flag = 10;
            ushort status_flag_old = 10;
            ushort runtype = 0;
          //  Modbus m_modbus = new Modbus();

            while (!conmre.WaitOne(500))
            {
                dest[0] = globaldata.m_hmibuffer.gcinfo.batno;
                dest[1] = globaldata.m_hmibuffer.gcinfo.batruncount;
                dest[2] = globaldata.m_hmibuffer.gcinfo.oneruntime;
                dest[3] = globaldata.m_hmibuffer.gcinfo.singlerun;
                dest[4] = globaldata.m_hmibuffer.gcinfo.batrun;
                dest[5] = globaldata.m_hmibuffer.gcinfo.methodstatus;
                dest[6] = globaldata.m_hmibuffer.gcinfo.waitstart;
                dest[7] = globaldata.m_hmibuffer.gcinfo.hmistatus;
                dest[8] = globaldata.m_hmibuffer.gcinfo.runtime;

                //if(globaldata.connection_ip !=null)
                //    ret = m_modbus.ReadHoldingReg(144, 9, globaldata.connection_ip, globaldata.datamodbusport, ref dest);
                //    //ret = globaldata.m_modbus.ReadHoldingReg(144, 9, globaldata.connection_ip, globaldata.datamodbusport, ref dest);

                //if(globaldata.system_Statue)
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                    status_flag = dest[5];
                else
                    status_flag = 10;

                GCstatus = dest[5];
                runtype = dest[7];

                globaldata.MethodRun_Statue = dest[5];
                globaldata.RunTime_Now = dest[2];
                globaldata.RunTotal_Now = dest[8];

                //Console.WriteLine("+++++++++++调试信息++++++++++++++");
                //Console.WriteLine("批处理序号：" + dest[0].ToString());
                //Console.WriteLine("运行次数：" + dest[1].ToString());
                //Console.WriteLine("运行多少秒：" + dest[2].ToString());
                //Console.WriteLine("单次运行：" + dest[3].ToString());
                //Console.WriteLine("运行运行表：" + dest[4].ToString());
                //Console.WriteLine("当前运行方法状态:" + dest[5].ToString());
                //Console.WriteLine("打开当前方法，等待开始指令：" + dest[6].ToString());
                //Console.WriteLine("机器运行状态：" + dest[7].ToString());
                //Console.WriteLine("运行总时间：" + dest[8].ToString());

                if(ret != 0)
                {
                    LoseNum++;
                    if(LoseNum > 4)
                    {
                    //    Console.WriteLine("断线了。。。");
                        status_flag = 9;
                       // globaldata.connection_ip = null;
                    }
                }else
                {
                    LoseNum = 0;
                }

                //if(dest[5] == 3 && dest[7] == 4)
                //{
                //    Console.WriteLine("已就绪！！！！！！！");
                //}

                if ((dest[5] == 4 || dest[5] == 5) && dest[7] == 4 && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue != 1)
                {
                   // Console.WriteLine("已就绪,下位机按了开始！！");
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 0;
                    invokeDelegate update_ButtonStatus = () =>
                    {
                        ChangeButton(2);
                    };
                    Invoke(update_ButtonStatus);                   
                    startbtn();
                }

                //点火失败或着火焰熄灭，停止系统
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue && globaldata.m_hmibuffer.gcinfo.FireStatus[0] == 3 && globaldata.m_hmibuffer.gcinfo.methodstatus == 0 && globaldata.m_hmibuffer.gcinfo.hmistatus == 0)
                {
                    invokeDelegate auto_close = () =>
                    {
                        autoclosesys_Click();                        
                    };
                    Invoke(auto_close);
                    
                }

                //if ( (dest[5] ==0 || dest[5] == 6 || dest[5] == 7 ) && dest[7] == 0 && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                //{
                //    Console.WriteLine("已就绪,下位机按了停止！！");
                //}

                //if (dest[5] == 0)
                //{
                //    globaldata.work_Statue = 0;
                //}

                switch(runtype)
                {
                    case 0:
                        ButtonControl_Status(dest[5], 0);
                        DataControl_Status(dest[5], 0);
                        break;
                    case 2:
                        BAT_HeadInfo(dest[0], dest[1]);
                        ButtonControl_Status(dest[5], 2);
                        DataControl_Status(dest[5], 2);
                        break;
                    case 3:
                        QuickRun_HeadInfo();
                        ButtonControl_Status(dest[5], 1);
                        DataControl_Status(dest[5], 1);
                        break;
                    case 4:
                        SingleRun_HeadInfo();
                        ButtonControl_Status(dest[5], 0);
                    //  DataControl_Status(dest[5], 0);
                        break;
                    default:
                        Common_HeadInfo();
                        break;
                }     
                Status_Show(status_flag, ref status_flag_old);
                Thread.Sleep(1000);
            }
        }

        public void Start_Thread()
        {
           // mydatasave.ChannelDataStart();
            mymodbus.HmiStatueStart();
            mymodbus.ChannelDataStart();
            dataVOC.CKvocUpdataStart();
        }

        public void Stop_Thread()
        {
           // mydatasave.ChannelDataStop();
            mymodbus.HmiStatueStop();
            mymodbus.ChannelDataStop();
            dataVOC.CKvocUpdataStop();
        }

        public void SetMainFormMethodName(string text)
        {
            this.now_method.Text = "当前运行方法：" + text;
        }

        public void SetTitleStatueName(string text, bool flag)
        {
            textconent.Text = text;
            if(flag)
            {
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));
            }else
            {
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(185)))), ((int)(((byte)(16)))));
            }           
        }
        
        public void SendStopCMD()
        {
            hmiopt.WriteStopVal();
            WaitHMIFree();
           // singlemodbus.WriteStopVal();
        }
      
        public void fireupopt(ushort time1, ushort time2)
        {
            hmiopt.FireUPWork(time1,time2);
           // singlemodbus.FireUPWork(time1, time2);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
            }
            else
            {
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 0; i < 100; i++)
            {
                if (globaldata.m_hmibuffer.gcinfo.methodstatus == 0)
                {
                    if (globaldata.OS_STOP)
                    {
                        globaldata.OS_STOP = false;
                    }
                   
                    worker.ReportProgress(100);
                    break;
                }else
                {
                    if(i%20 == 0)
                    {
                        if(globaldata.OS_STOP)
                        {
                            hmiopt.WriteEndVal();
                        }else
                        {
                            hmiopt.WriteStopVal();
                        }
                        
                    }

                    Thread.Sleep(100);
                    if(i != 99)
                        worker.ReportProgress(i);
                }
                           
                if (worker.CancellationPending)  // 如果用户取消则跳出处理数据代码 
                {
                    e.Cancel = true;
                    break;
                }
            }
        }

        public void WaitHMIFree()
        {
            this.backgroundWorker1.RunWorkerAsync();
            WaitForm form = new WaitForm(this.backgroundWorker1);
            form.ShowDialog(this);
            form.Close();
        }


        private void bgWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
            }
            else
            {
            }
        }

        private void bgWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 0; i < 100; i++)
            {
                if (globaldata.m_hmibuffer.gcinfo.methodstatus > 0 && globaldata.m_hmibuffer.gcinfo.methodstatus < 5)
                {
                    worker.ReportProgress(100);
                    break;
                }
                else
                {
                    if(i%20 == 0 && i != 0)
                    {
                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                            hmiopt.WriteOpenVal();
                       // singlemodbus.WriteOpenVal();

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                        hmiopt.WriteSingleVal();
                       // singlemodbus.WriteSingleVal();

                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                        {
                            // singlemodbus.WriteBatVal();
                            hmiopt.WriteBatVal();
                            // singlemodbus.WriteStartVal();
                            hmiopt.WriteStartVal();
                        }
                    }

                    Thread.Sleep(100);
                    if (i <= 99)
                        worker.ReportProgress(i);
                }

                if (worker.CancellationPending)  // 如果用户取消则跳出处理数据代码 
                {
                    e.Cancel = true;
                    break;
                }
            }
        }

        public void WaitHMIWork()
        {
            this.bgWorker2.RunWorkerAsync();
            WaitForm form = new WaitForm(this.bgWorker2);
            form.ShowDialog(this);
            form.Close();
        }


        public void SendPCCMD(bool flag)
        {
            if (flag)  //打开运行
            {
                hmiopt.WriteStopVal();
                //singlemodbus.WriteStopVal();
                WaitHMIFree();
               
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                {
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                        hmiopt.WriteStopVal();
                        //singlemodbus.WriteOpenVal();

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                        hmiopt.WriteSingleVal();
                       // singlemodbus.WriteSingleVal();

                    WaitHMIWork();
                }

                

            }else   //批处理
            {
                hmiopt.WriteStopVal();
               // singlemodbus.WriteStopVal();
                WaitHMIFree();

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                {
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        hmiopt.WriteBatVal();
                        //singlemodbus.WriteBatVal();
                        hmiopt.WriteStartVal();
                       // singlemodbus.WriteStartVal();
                        WaitHMIWork();
                    }
                    
                }
            }        
        }

        /// <summary>
        /// 检测本地默认目录
        /// </summary>
        private void MainBase_InitAppConfig()
        {
            string tmpFolder;
            //检查创建仪器方法目录
           // globaldata.RunFolder = System.Windows.Forms.Application.StartupPath;
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder = System.Windows.Forms.Application.StartupPath;
            tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder;

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder = System.IO.Path.Combine(tmpFolder, "仪器方法");
           // globaldata.MethodFolder = System.IO.Path.Combine(globaldata.RunFolder, "仪器方法");
            tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder;

          //  globaldata.cur_MethodName =System.IO.Path.Combine(globaldata.MethodFolder, "SingleAnal.ini(单次运行默认方法)");
            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = System.IO.Path.Combine(tmpFolder, "SingleAnal.ini(单次运行默认方法)");
            tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder;
            if (System.IO.Directory.Exists(tmpFolder) == false)
            {
                System.IO.Directory.CreateDirectory(tmpFolder);
            }

            //检查创建仪器状态目录
            tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder;
           // globaldata.StatusFolder = System.IO.Path.Combine(globaldata.RunFolder, "仪器状态");
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder = System.IO.Path.Combine(tmpFolder, "仪器状态");
            tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder;
            if (System.IO.Directory.Exists(tmpFolder) == false)
            {
                System.IO.Directory.CreateDirectory(tmpFolder);
            }

           // globaldata.cur_StatusName = System.IO.Path.Combine(globaldata.StatusFolder, "DevStatus.ini");
            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName = System.IO.Path.Combine(tmpFolder, "DevStatus.ini");

            if (globaldata.connection_ip == null && System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName) == false)
            {
                System.IO.File.Create(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName).Dispose();
            }

          //  globaldata.subStatusFolder = System.IO.Path.Combine(globaldata.StatusFolder, "子状态");
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.subStatusFolder = System.IO.Path.Combine(tmpFolder, "子状态");
            if (System.IO.Directory.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.subStatusFolder) == false)
            {
                System.IO.Directory.CreateDirectory(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.subStatusFolder);
            }
            
            //globaldata.m_profileMethod.SetStatusFullName(globaldata.cur_StatusName);
            globaldata.m_profileMethod.SetStatusFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName);

            //检查创建运行表目录
            //globaldata.RunTabFolder = System.IO.Path.Combine(globaldata.RunFolder, "运行表");
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder, "运行表");
            //globaldata.cur_RunTab = System.IO.Path.Combine(globaldata.RunTabFolder, "RunMethod.ini");
            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, "RunMethod.ini");

            if (System.IO.Directory.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder) == false)
            {
                System.IO.Directory.CreateDirectory(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder);
            }
            if (System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab) == false)
            {
                StreamWriter sw = new StreamWriter(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab, false, System.Text.Encoding.Unicode);
                sw.WriteLine("[运行表]");
                sw.Close();
            }

            //globaldata.DataFolder = System.IO.Path.Combine(globaldata.RunFolder, "历史数据");
            //globaldata.cur_DataName = null;

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder, "历史数据");
            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_DataName = null;
           // globaldata.cur_DataName = null;

            if (System.IO.Directory.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder) == false)
            {
                System.IO.Directory.CreateDirectory(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder);
            }

            tmpFolder = null;
        }

        /// <summary>
        /// 初始化标题栏
        /// </summary>
        private void ManinBase_InitFormTitle()
        {
            string tmpFileName;
            this.mixlogo.Image = logoList.Images[0];
            this.companyname.Text = "Tet-chrom";
            this.softname.Text = "泰特色谱软件";
            this.softversion.Text = "V1.0.1";

            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;

            if (tmpFileName == null)
            {
                this.now_method.Text = "当前运行方法： 未加载";
            }
            else
            {
                this.now_method.Text = "当前运行方法：" + tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1);
            }   
        }

        /// <summary>
        /// 初始化菜单栏
        /// </summary>
        private void MainBase_InitFromMenu()
        {
            int tagnum;
            //添加panelmemu里面内容
            for (int i = 0; i < 15; i++)
            {
                if (i != 10)
                {
                    PictureBox picture = new PictureBox();
                    picture.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(243)))));
                   
                    if(i > 10)
                    {
                        picture.Image = this.menuList.Images[i-1];
                        picture.Tag = i - 1;
                        picture.TabIndex = i - 1;
                    }
                    else
                    {
                        //if(i < 3)
                        //{
                        //    picture.Image = this.menuList.Images[i+14];
                        ////    picture.Enabled = false;
                        //}else
                        //{
                            picture.Image = this.menuList.Images[i];
                       // }                       
                        picture.Tag = i;
                        picture.TabIndex = i;
                    }
                   
                    picture.Size = new System.Drawing.Size(57, 57);
                  
                    picture.Name = "menubtn" + i.ToString();
                   
                    picture.TabStop = false;
                    this.panelMenu.Controls.Add(picture);
                }
                else
                {
                    Panel textPanel = new Panel();
                    textPanel.Name = "panel1";
                    textPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(243)))));
                    textPanel.Size = new System.Drawing.Size(100, 62);
                    textPanel.TabIndex = 10;
                    this.panelMenu.Controls.Add(textPanel);
                }
            }


            try
            {
                foreach (Control c in panelMenu.Controls)
                {
                    if (c is PictureBox)
                    {
                         tagnum = Convert.ToInt32(c.Tag);
                        if(tagnum > 2 && tagnum < 13)
                        {
                            c.MouseDown += new MouseEventHandler(btn_MouseDown);
                            c.MouseHover += new EventHandler(btn_MouseHover);
                            c.MouseLeave += new EventHandler(btn_MouseLeave);
                            c.MouseUp += new MouseEventHandler(btn_MouseUp);                          
                        }
                        
                        if(tagnum >=0 && tagnum <=2)
                        {
                           // c.Image = menuList.Images[tagnum + 14];
                          //     c.MouseDown += new MouseEventHandler(contrl_MouseDown);
                          //  c.MouseHover += new EventHandler(contrl_MouseHover);
                          //  c.MouseLeave += new EventHandler(contrl_MouseLeave);
                          //     c.MouseUp += new MouseEventHandler(contrl_MouseUp);
                        }

                        if(tagnum == 13)
                        {
                           // c.Click += new EventHandler(btn_Click);
                        }

                        c.Click += new EventHandler(btn_Click);
                        
                    }
                }
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }

            Label runtime = new Label();
            runtime.Text = DateTime.Now.ToString("hh:mm:ss");
            runtime.Location = new Point(0,30);

            textconent = new TextBox();
            textconent.Enabled = false;
            textconent.Width = 100;

            if (globaldata.connection_ip != null)
            {
                textconent.Text = "设备联机...";
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));
            }
            else
            {
                textconent.Text = "未联机...";
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(185)))), ((int)(((byte)(16)))));
            }
            textconent.BackColor = Color.White;
            ((Panel)this.panelMenu.Controls[10]).Controls.Add(textconent);
            ((Panel)this.panelMenu.Controls[10]).Controls.Add(runtime);

           //// PID测试
           // Button pidtest = new Button();
           // pidtest.Height = 50;
           // pidtest.Width = 50;
           // pidtest.Text = "PID测试";
           // pidtest.Click += new EventHandler(pidtest_test);
           // this.panelMenu.Controls.Add(pidtest);
            // ((Panel)this.panelMenu.Controls[15]).Controls.Add(pidtest);

            //文件更新
            //Button filetest = new Button();
            //filetest.Height = 50;
            //filetest.Width = 50;
            //filetest.Text = "更新测试";
            //filetest.Click += new EventHandler(filetest_test);
            //this.panelMenu.Controls.Add(filetest);
            
            ////初始化开始，停止，取消
            ((PictureBox)panelMenu.Controls[0]).Image = this.menuList.Images[14];
            ((PictureBox)panelMenu.Controls[1]).Image = this.menuList.Images[15];
            ((PictureBox)panelMenu.Controls[2]).Image = this.menuList.Images[16];

        }
     
        private void contrl_MouseUp(object sender, MouseEventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
                picturebtn.Image = menuList.Images[tagnum + 14];          
        }

        private void contrl_MouseLeave(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);
       //     if (globaldata.system_Statue == true)
       //         picturebtn.Image = menuList.Images[tagnum];
           
        }

        private void contrl_MouseHover(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
                picturebtn.Image = menuList.Images[tagnum + 28];  
            
        }

        private void contrl_MouseDown(object sender, MouseEventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
                picturebtn.Image = menuList.Images[tagnum + 14];     
        }

        /// <summary>
        /// PID测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pidtest_test(object sender, EventArgs e)
        {
            //PID_Form pidf = new PID_Form();
            //pidf.Show();
        }

        /// <summary>
        /// 文件测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void filetest_test(object sender, EventArgs e)
        {
            UpdateTest filetest = new UpdateTest();
            filetest.Show();
        }
      
        private void Load_Win()
        {
            string singlefilename = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, "SingleAnal.ini");
            string tmpname;

            int ret;

            if (globaldata.connection_ip != null)
            {
                //获取配置文件
                try
                {                 
                    FileServerClient mainclient = new FileServerClient();
                    mainclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);                
                    if (System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName))
                    {
                        Thread.Sleep(100);
                        System.IO.File.Delete(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName);                                                                                        
                    }
                    ret = mainclient.WtClientCopyfromServer("DevStatus.ini", globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName, "\\Hard Disk\\仪器状态\\");
                    Thread.Sleep(400);

                    if (System.IO.File.Exists(singlefilename))
                    {                       
                       System.IO.File.Delete(singlefilename);                                                         
                    }
                    ret = mainclient.WtClientCopyfromServer("SingleAnal.ini", singlefilename, "\\Hard Disk\\仪器方法\\");                    
                    Thread.Sleep(400);

                    mainclient.WtClientClose();

                    globaldata.m_profileMethod.GetDevState();
                    INIOperation GetMethodName = new INIOperation(singlefilename);
                    tmpname = GetMethodName.INIGetStringValue("方法名称", "名称", null);

                    if(tmpname != null)
                    {
                        globaldata.show_MethodName = tmpname;
                        this.now_method.Text = "当前运行方法：" + tmpname;

                        //globaldata.cur_MethodName = System.IO.Path.Combine(globaldata.MethodFolder, tmpname.ToString());
                        globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, tmpname.ToString());
                        globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);

                        globaldata.m_profileMethod.GetDevInjPortAllPara();
                        globaldata.m_profileMethod.GetSampleAllPara("前进样器");
                        globaldata.m_profileMethod.GetInjValveAllPara();
                        globaldata.m_profileMethod.GetChromAllPara();
                        globaldata.m_profileMethod.GetColTableElseAllPara();
                        globaldata.m_profileMethod.GetFidAllPara();
                        globaldata.m_profileMethod.GetTcdAllPara();
                        globaldata.m_profileMethod.GetAuxiliaryAllPara();                  
                    }                 
                }
                catch (Exception e)
                {
                   // string message = "系统初始化失败，请关闭重新打开...";
                    MessageBox.Show(e.ToString(), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);                 
                }
                
                textconent.Text = "设备联机";
            //    curdisplay.Text = "实时监控设备:" + CProfileDevice.m_DevParam.syspara.GCName;
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));
            }
            else
            {
                
                textconent.Text = "未联机";
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(185)))), ((int)(((byte)(16)))));
             //   curdisplay.Text = "实时监控设备：";
            }


            this.showPanel.Contains(curdisplay);

            curdisplay.Show(this.showPanel);
            curdisplay.CloseButtonVisible = false;
            // curdisplay.Show(this.showPanel);
            //curdisplay.CloseButtonVisible = false;
          //  curdisplay.Show(this.showPanel);
          //  curdisplay.CloseButtonVisible = false;
                //singlemodbus = null;
                //singlemodbus = new GcDataReq(globaldata.connection_ip, globaldata.datamodbusport);

                hmiopt = null;
                hmiopt = new HMIControl(globaldata.connection_ip, globaldata.datamodbusport);
                mymodbus = null;
                mymodbus = new GcDataTh(globaldata.connection_ip, globaldata.datamodbusport);

                Stop_Thread();
                Start_Thread();

                dockPanelSideLeft.Close_Threading();
                dockPanelSideLeft.Close();

                //uitest.Close();
                //uitest = new Test();
                //uitest.Show(this.showPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockBottom);
                //uitest.CloseButtonVisible = false;

                //侧边状态菜单
                dockPanelSideLeft = new DataState();
                dockPanelSideLeft.Show(this.showPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockRight);
                dockPanelSideLeft.CloseButtonVisible = false;
               
        }

        private void MainBase_Load(object sender, EventArgs e)
        {

            //if (f_netconfig.IsDisposed)
            //{
            //    f_netconfig = new ListViewTest();
            //}

            globaldata.starttimer = 0x7FFFFFFF;
            Console.WriteLine("MainBase_Load  MainBase_Load");
            //f_netconfig.MainBase_Load += new ChangeMainShow(MainBase_Load);
            Load_Win();
            //this.windowState = FormWindowState.Maximized;

            string file = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder + "\\startup.ini";
            INIOperation test = new INIOperation(file);
            string opensys = test.INIGetStringValue("StartUp", "打开系统", "0");
           // string runtype = test.INIGetStringValue("StartUp", "运行类型", null);

            if (Convert.ToInt32(opensys) == 1 && globaldata.m_hmibuffer.gcinfo.methodstatus == 0)
            {
                autoopensys_Click();
            }

            if (globaldata.m_hmibuffer.gcinfo.methodstatus != 0)
            {
                hmistatus_opensys();
            }

            //this.panelMenu.Controls[0].Enabled = true;
            //this.panelMenu.Controls[1].Enabled = false;
            //this.panelMenu.Controls[2].Enabled = false;
        }

        private void btn_Click(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);

            switch (tagnum)
            {
                case 0:
                    Startbtn_Click(sender, e);  //开始
                    break;
                case 1:
                    Stopbtn_Click(sender, e);  //停止
                    break;
                case 2:
                    Cancelbtn_Click(sender, e);   //取消
                    break;
                case 3:
                    newbtn_Click(sender, e);   //新建方法
                    break;
                case 4:
                    browse_Click(sender, e);   //打开方法  
                    break;
                case 5:
                  //  SingleAnal_Click(sender, e);  //快速运行
                    helptool_Click(sender, e);
                    break;
                case 6:
                    batdeal_Click(sender, e);    //智能运行          
                    break;
                case 7:
                    openbtn_Click(sender, e);    //方法查询                 
                    break;
                case 8:
                    netcfg_Click(sender, e);    //通讯设置          
                    break;
                case 9:
                    showcfg_Click(sender, e);   //仪器配置
                    break;
                case 10:
                    showdata_Click(sender,e);  //数据查询
                    break;
                case 11:
                    datacalibration_Click(sender,e); //数据校准
                    break;
                case 12:
                    historyrec_Click(sender,e);  //历史文件
                    break;
                case 13:
                    openSys_Click(sender, e);      //开启系统        
                    break;
            }
        }

        bool OSflag = false;
        private void hmistatus_opensys()
        {
            if (globaldata.connection_ip != null)
            {
                if (!OSflag)
                {
                    OSflag = !OSflag;
                
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                       // hmiopt.WriteBatVal();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteOpenVal();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                    {
                      //  hmiopt.WriteSingleVal();
                    }

                    int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                    ((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum + 14];
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = true;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                }
               
            }
            else
            {
                string message = "系统处于离线状态...";
                MessageBox.Show(message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
        }

        /// <summary>
        /// 自动停止系统
        /// </summary>
        private void autoclosesys_Click()
        {
            if (globaldata.connection_ip != null)
            {                              
                    OSflag = !OSflag;
                    SetTitleStatueName("系统停止中...", false);
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();
                    WaitHMIFree();
                    SetTitleStatueName("系统停止...", false);

                    int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                    ((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum];

                    ((PictureBox)panelMenu.Controls[0]).Enabled = false;
                    ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                    ((PictureBox)panelMenu.Controls[1]).Enabled = false;
                    ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[15];
                    ((PictureBox)panelMenu.Controls[2]).Enabled = false;
                    ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[16];

                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
            else
            {
                string message = "系统处于离线状态...";
                MessageBox.Show(message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
        }



        private void autoopensys_Click()
        {
            if (globaldata.connection_ip != null)
            {
                if (!OSflag)
                {
                    OSflag = !OSflag;
                    hmiopt.WriteStopVal();                    
                    SetTitleStatueName("系统准备中...", true);
                    WaitHMIFree();

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        hmiopt.WriteBatVal();                                 
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteOpenVal();                       
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                    {
                        hmiopt.WriteSingleVal();                      
                    }

                    WaitHMIWork();

                    Thread.Sleep(500);

                    int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                    ((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum + 14];
                   
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = true;                  
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;

                }
                else
                {
                    OSflag = !OSflag;                    
                    SetTitleStatueName("系统停止中...", false);
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();                  
                    WaitHMIFree();
                    SetTitleStatueName("系统停止...", false);

                    int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                    ((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum];

                    ((PictureBox)panelMenu.Controls[0]).Enabled = false;
                    ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                    ((PictureBox)panelMenu.Controls[1]).Enabled = false;
                    ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[15];
                    ((PictureBox)panelMenu.Controls[2]).Enabled = false;
                    ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[16];
                    
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;                    
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                }
            }
            else
            {
                string message = "系统处于离线状态...";
                MessageBox.Show(message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);              
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
        }


        private void openSys_Click(object sender, EventArgs e)
        {
            if (globaldata.connection_ip != null)
            {   
                if (!OSflag)
                {
                    OSflag = !OSflag;
                    hmiopt.WriteStopVal();
                    SetTitleStatueName("系统准备中...", true);
                    WaitHMIFree();
                 
                    if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        hmiopt.WriteBatVal();                 
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteOpenVal();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                    {
                        hmiopt.WriteSingleVal();
                    }

                    WaitHMIWork();

                    Thread.Sleep(500);

                    int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                    ((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum + 14];
                                    
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = true;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                    globaldata.starttimer = 0;
                    globaldata.startimerIsSet = true;

                }else
                {
                    OSflag = !OSflag;                  
                    SetTitleStatueName("系统停止中...", false);
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();                   
                    WaitHMIFree();
                    SetTitleStatueName("系统停止...", false);

                    int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                    ((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum];

                    ((PictureBox)panelMenu.Controls[0]).Enabled = false;
                    ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                    ((PictureBox)panelMenu.Controls[1]).Enabled = false;
                    ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[15];
                    ((PictureBox)panelMenu.Controls[2]).Enabled = false;
                    ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[16];
                  
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;                 
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                }                
            }
            else
            {
                string message = "系统处于离线状态...";
                MessageBox.Show(message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);             
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
        }

        private void historyrec_Click(object sender, EventArgs e)
        {
            //int ret;

            //if (globaldata.m_configDlg.Visible == true)
            //    return;

            //OpenFileDialog fileDlg = new OpenFileDialog();
            //fileDlg.Multiselect = false;
            //fileDlg.InitialDirectory = Application.StartupPath + "\\历史数据";
            //fileDlg.Title = "请选择方法文件";
            //fileDlg.Filter = "配置文件(*.tw)|*.tw";
            //if (fileDlg.ShowDialog() == DialogResult.OK)
            //{
            //    string file = fileDlg.FileName;
            //    file = file.Substring(file.LastIndexOf("\\") + 1);
            //    //enableforhd(file);  
            //  //  this.curdisplay.enable_for_HD(file);
            //}

            //if(Historical_Atlas.IsDisposed)
            //{
            //    Historical_Atlas = new Form5();
            //    Historical_Atlas.Show();

            //}else
            //{
            //    Historical_Atlas.Show();
            //}         
        }

        private void datacalibration_Click(object sender, EventArgs e)
        {
            if (dataadjust.IsDisposed)
            {
                dataadjust = new AdjustFrom();
                dataadjust.Show();
            }
            else
            {
                dataadjust.Show();
            }
        }


        private void helptool_Click(object sender, EventArgs e)
        {
            ushort[] firetime = new ushort[2];
            mymodbus.GetFireUpTime(ref firetime);

            if(f_auxtool == null)
            {
                f_auxtool = new auxtool(firetime[0], firetime[1]);
                f_auxtool.auxtoolforfireup -= new AUXTool(fireupopt);
                f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                f_auxtool.auxtoolforfireup -= new AUXTool(fireupopt);
                f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                f_auxtool.Show();
            }else
            {
                if (f_auxtool.IsDisposed)
                {
                    f_auxtool = new auxtool(firetime[0], firetime[1]);
                    f_auxtool.auxtoolforfireup -= new AUXTool(fireupopt);
                    f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                    f_auxtool.auxtoolforfireup -= new AUXTool(fireupopt);
                    f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                    f_auxtool.Show();
                }
                else
                {
                    f_auxtool.auxtoolforfireup -= new AUXTool(fireupopt);
                    f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                    f_auxtool.auxtoolforfireup -= new AUXTool(fireupopt);
                    f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                    f_auxtool.Show();
                }
            }
        }



        private void batdeal_Click(object sender, EventArgs e)
        {
            if (f_runtable.IsDisposed)
            {
                f_runtable = new RunTables();
                f_runtable.sendupdatecmd -= new SendUpdateCMD(SendPCCMD);
                f_runtable.sendupdatecmd += new SendUpdateCMD(SendPCCMD);
                f_runtable.sendstopcmd -= new SendStopCMD(SendStopCMD);
                f_runtable.sendstopcmd += new SendStopCMD(SendStopCMD);
                f_runtable.Show();
            }
            else
            {
                f_runtable.sendupdatecmd -= new SendUpdateCMD(SendPCCMD);
                f_runtable.sendupdatecmd += new SendUpdateCMD(SendPCCMD);
                f_runtable.sendstopcmd -= new SendStopCMD(SendStopCMD);
                f_runtable.sendstopcmd += new SendStopCMD(SendStopCMD);
                f_runtable.Show();
            }
        }

        private void savebtn_Click(object sender, EventArgs e)
        {
            //if (globaldata.cur_MethodName != null)
            //    globaldata.m_configDlg.Save_Method();
            if (globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName != null || globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName !=null)
                globaldata.m_configDlg.Save_Method();
        }

        private void btn_MouseDown(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);           
            picturebtn.Image = menuList.Images[tagnum + 14];
        }

        private void btn_MouseUp(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);            
            picturebtn.Image = menuList.Images[tagnum + 14];
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);                                   
            picturebtn.Image = menuList.Images[tagnum + 14];                                                    
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);           
            picturebtn.Image = menuList.Images[tagnum];        
        }

        //标题栏 最小化，全屏切换，关闭事件
        private void mixbtn_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void changebtn_Click(object sender, EventArgs e)
        {
            if (this.changebtn.Text == "口")
                this.windowState = FormWindowState.Maximized;
            else
                this.windowState = FormWindowState.Normal;
        }

        public System.Windows.Forms.DialogResult ShowQuitBox()
        {
            return new QuitForm().ShowDialog();
        }

        private void closebtn_Click(object sender, EventArgs e)
        {

            DialogResult dr;
            dr = ShowQuitBox();

            if(dr == DialogResult.OK)  //停止系统并退出
            {
                if(globaldata.connection_ip != null)
                {
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();
                    WaitHMIFree();
                }              
                System.Environment.Exit(0);
            }

            if(dr == DialogResult.Yes)  //仅退出
            {
                if(globaldata.connection_ip != null)
                {
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        hmiopt.WriteStopVal();
                        WaitHMIFree();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteOpenVal();
                        WaitHMIWork();
                    }
                }
                System.Environment.Exit(0);
            }

            


            //if(globaldata.m_hmibuffer.gcinfo.methodstatus != 0)
            //{
            //    if (DialogResult.Yes == MessageBox.Show("方法运行中,确认退出?", "提示消息", MessageBoxButtons.YesNo))
            //    {
            //        hmiopt.WriteStopVal();
            //        WaitHMIFree();
            //        System.Environment.Exit(0);
            //    }   
            //}else
            //{
            //    if (DialogResult.Yes == MessageBox.Show("程序正在使用中,确认退出?", "提示消息", MessageBoxButtons.YesNo))
            //    {
            //       // hmiopt.WriteStopVal();
            //        System.Environment.Exit(0);
            //    }   
            //}

                   
        }

        public FormWindowState windowState
        {
            get
            {
                return this.WindowState;
            }
            set
            {
                if (value == FormWindowState.Normal)
                {
                    this.changebtn.Text = "口";
                    this.WindowState = FormWindowState.Normal;
                }
                else if (value == FormWindowState.Maximized)
                {
                    this.changebtn.Text = "吕";
                    this.WindowState = FormWindowState.Maximized;
                }
            }
        }

        private void paneltitle_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.WindowState = this.WindowState == FormWindowState.Normal ? FormWindowState.Maximized : FormWindowState.Normal;
            if (this.WindowState == FormWindowState.Normal)
            {
                this.changebtn.Text = "口";
            }
            else
            {
                this.changebtn.Text = "吕";
            }
        }

        //窗口变化自适应
        private void MainBase_SizeChanged(object sender, EventArgs e)
        {
            //改变标题栏
            this.paneltitle.Width = this.Width;
            Point closep = new Point(this.Width - 30, 0);
            this.closebtn.Location = closep;
            Point changep = new Point(this.Width - 60, 0);
            this.changebtn.Location = changep;
            Point mixp = new Point(this.Width - 90, 0);
            this.mixbtn.Location = mixp;

            this.panelMenu.Width = this.Width;

            this.showPanel.Width = this.Width;
            this.showPanel.Height = this.Height - this.paneltitle.Height - this.panelMenu.Height;
        }

        private void paneltitle_MouseDown(object sender, MouseEventArgs e)
        {
           if (e.Button == MouseButtons.Left)
            {
                dwPoint = new Point(-e.X, -e.Y);
                moveFlag = true;
            }
        }

        private void paneltitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (moveFlag)
            {
                Point mousePoint = Control.MousePosition;
                mousePoint.Offset(dwPoint.X, dwPoint.Y);
                Location = mousePoint;
            }
        }

        private void paneltitle_MouseUp(object sender, MouseEventArgs e)
        {
            if (moveFlag)
            {
                moveFlag = false;
            }
        }

        //网络配置事件
        private void netcfg_Click(object sender, EventArgs e)
        {
            // this.netcfg.Image = menuList.Images[25];
            //if (f_netconfig.IsDisposed)
            //{
            //    f_netconfig = new ListViewTest();
            //    f_netconfig.MainBase_Load += new ChangeMainShow(MainBase_Load);
            //    f_netconfig.Show();
            //}
            //else
            //{
            //    f_netconfig.Show();
            //}

            if (appstartup.IsDisposed)
            {
                appstartup = new UserConfig();
                appstartup.Show();
            }
            else
            {
                appstartup.Show();
            }



        }

        private void showcfg_Click(object sender, EventArgs e)
        {
            if (f_showcfg.IsDisposed)
            {
                f_showcfg = new InstrConfig();
                f_showcfg.Show();
            }
            else
            {
                f_showcfg.Show();
            }
        }

        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDlg = new OpenFileDialog();
            fileDlg.Multiselect = false;
            fileDlg.InitialDirectory = Application.StartupPath + "\\仪器方法";
            fileDlg.Title = "请选择方法文件";
            fileDlg.Filter = "配置文件(*.ini)|*.ini";
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                string file = fileDlg.FileName;
               // globaldata.cur_MethodName = file;
               // globaldata.cur_OpenMethodName = file;
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName = file;
                this.inifilec = true;

                globaldata.m_profileMethod.SetMethodFullName(file);
                globaldata.m_profileMethod.GetDevState();

                if (globaldata.m_configDlg.IsDisposed)
                    globaldata.m_configDlg = new MethodConfig();

                globaldata.m_configDlg.m_InjPortDlg.reflashContent();
                globaldata.m_configDlg.m_InjSampleDlg.reflashContent();
                globaldata.m_configDlg.m_InjValveDlg.reflashContent();
                globaldata.m_configDlg.m_chromeDlg.reflashContent();
                globaldata.m_configDlg.m_RealColDlg.reflashContent();
                globaldata.m_configDlg.m_det.reflashContent();
                globaldata.m_configDlg.m_AuxDlg.reflashContent();

                globaldata.m_configDlg.changenameforup -= new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                globaldata.m_configDlg.changenameforup += new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                globaldata.m_configDlg.sendupdatecmd -= new ConfigDlg.SendUpdateCMD(SendPCCMD);
                globaldata.m_configDlg.sendupdatecmd += new ConfigDlg.SendUpdateCMD(SendPCCMD);
                globaldata.m_configDlg.Show();

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 0;
                //globaldata.RunType = 0;
                //  globaldata.m_configDlg.m_RunTableDlg.reflashContent();
            }



            //OpenFileDialog fileDlg = new OpenFileDialog();
            //fileDlg.Multiselect = false;
            //fileDlg.InitialDirectory = Application.StartupPath + "\\仪器方法";
            //fileDlg.Title = "请选择方法文件";
            //fileDlg.Filter = "配置文件(*.ini)|*.ini";
            //int ret;

            //if (fileDlg.ShowDialog() == DialogResult.OK)
            //{
            //    string file = fileDlg.FileName;
            //    globaldata.cur_MethodName = file;
            //    this.inifilec = true;

            //    globaldata.m_profileMethod.SetMethodFullName(file);
            //    globaldata.m_profileMethod.GetDevState();

            //    if (globaldata.m_configDlg.IsDisposed)
            //        globaldata.m_configDlg = new MethodConfig();

            //    this.now_method.Text = "当前运行方法：" + globaldata.cur_MethodName.Substring(globaldata.cur_MethodName.LastIndexOf("\\") + 1);

            //    if (globaldata.connection_ip != null)
            //    {
            //        singlemodbus.WriteStopVal();
           
            //        this.backgroundWorker1.RunWorkerAsync();
            //        WaitForm form = new WaitForm(this.backgroundWorker1);
            //        form.ShowDialog(this);
            //        form.Close();
                   

            //        string tmpname = globaldata.cur_MethodName.Substring(globaldata.cur_MethodName.LastIndexOf("\\") + 1);
            //        FileServerClient singlesend = new FileServerClient();
            //        singlesend.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
            //        ret = singlesend.WtClientCopytoServer("SingleAnal.ini", globaldata.cur_MethodName, "\\Hard Disk\\仪器方法\\");

            //       // ret = singlesend.WtClientCopytoServer(tmpname, globaldata.cur_MethodName, "\\Hard Disk\\仪器方法\\");

            //        singlesend.WtClientClose();

            //        globaldata.RunType = 0;

            //        if (inifilec && globaldata.system_Statue)
            //        {
            //            singlemodbus.WriteOpenVal();
            //        }
            //    }
            //}
        }

        private void newbtn_Click(object sender, EventArgs e)
        {
            if (m_methodNameInputForm.IsDisposed)
            {
                m_methodNameInputForm = new MethodNameInputForm();
                m_methodNameInputForm.Show();
            }
            else
            {
                m_methodNameInputForm.Show();
            }
        }

        private void openbtn_Click(object sender, EventArgs e)
        {
            if (globaldata.m_configDlg.Visible == true)
                return;

            if (inifilec)
            {
                globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);
                globaldata.m_profileMethod.GetDevState();

                if (globaldata.m_configDlg.IsDisposed)
                    globaldata.m_configDlg = new MethodConfig();

                globaldata.m_configDlg.m_InjPortDlg.reflashContent();
                globaldata.m_configDlg.m_InjSampleDlg.reflashContent();
                globaldata.m_configDlg.m_InjValveDlg.reflashContent();
                globaldata.m_configDlg.m_chromeDlg.reflashContent();
                globaldata.m_configDlg.m_RealColDlg.reflashContent();
                globaldata.m_configDlg.m_det.reflashContent();
                globaldata.m_configDlg.m_AuxDlg.reflashContent();

                globaldata.m_configDlg.changenameforup -= new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                globaldata.m_configDlg.changenameforup += new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);

                globaldata.m_configDlg.sendupdatecmd -= new ConfigDlg.SendUpdateCMD(SendPCCMD);
                globaldata.m_configDlg.sendupdatecmd += new ConfigDlg.SendUpdateCMD(SendPCCMD);

                globaldata.m_configDlg.Show();

            }
            else
            {
                OpenFileDialog fileDlg = new OpenFileDialog();
                fileDlg.Multiselect = false;
                fileDlg.InitialDirectory = Application.StartupPath + "\\仪器方法";
                fileDlg.Title = "请选择方法文件";
                fileDlg.Filter = "配置文件(*.ini)|*.ini";
                if (fileDlg.ShowDialog() == DialogResult.OK)
                {
                    string file = fileDlg.FileName;
                  //  globaldata.cur_MethodName = file;
                    //globaldata.cur_OpenMethodName = file;
                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName = file;

                    globaldata.m_profileMethod.SetMethodFullName(file);
                    globaldata.m_profileMethod.GetDevState();

                    if (globaldata.m_configDlg.IsDisposed)
                        globaldata.m_configDlg = new MethodConfig();

                    globaldata.m_configDlg.m_InjPortDlg.reflashContent();
                    globaldata.m_configDlg.m_InjSampleDlg.reflashContent();
                    globaldata.m_configDlg.m_InjValveDlg.reflashContent();
                    globaldata.m_configDlg.m_chromeDlg.reflashContent();
                    globaldata.m_configDlg.m_RealColDlg.reflashContent();
                    globaldata.m_configDlg.m_det.reflashContent();
                    globaldata.m_configDlg.m_AuxDlg.reflashContent();

                    globaldata.m_configDlg.changenameforup -= new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                    globaldata.m_configDlg.changenameforup += new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                    globaldata.m_configDlg.sendupdatecmd -= new ConfigDlg.SendUpdateCMD(SendPCCMD);
                    globaldata.m_configDlg.sendupdatecmd += new ConfigDlg.SendUpdateCMD(SendPCCMD);
                    globaldata.m_configDlg.Show();
                    //  globaldata.m_configDlg.m_RunTableDlg.reflashContent();
                }
            }       
        }

        private void SingleAnal_Click(object sender, EventArgs e)
        {
            if (globaldata.m_configDlg.Visible == true)
                return;

            if(this.inifilec)
            {
                if (globaldata.connection_ip != null)
                {
                    FileServerClient singlesend = new FileServerClient();
                    singlesend.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                    singlesend.WtClientCopytoServer("SingleAnal.ini", globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName, "\\Hard Disk\\仪器方法\\");
                    singlesend.WtClientClose();

                    hmiopt.WriteStopVal();
                    //singlemodbus.WriteStopVal();
                    WaitHMIFree();
                    hmiopt.WriteSingleVal();
                    //singlemodbus.WriteSingleVal();
               
                    textconent.Text = "快速运行...";
                    textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));

                    now_method.Text = "当前运行方法：" + globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.Substring(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.LastIndexOf("\\") + 1);

                }

            }else
            {
                OpenFileDialog fileDlg = new OpenFileDialog();
                fileDlg.Multiselect = false;
                fileDlg.InitialDirectory = Application.StartupPath + "\\仪器方法";
                fileDlg.Title = "请选择方法文件";
                fileDlg.Filter = "配置文件(*.ini)|*.ini";
                if (fileDlg.ShowDialog() == DialogResult.OK)
                {
                    string file = fileDlg.FileName;
                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = file;

                    if (globaldata.connection_ip != null)
                    {
                        FileServerClient singlesend = new FileServerClient();
                        singlesend.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                        singlesend.WtClientCopytoServer("SingleAnal.ini", globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName, "\\Hard Disk\\仪器方法\\");
                        singlesend.WtClientClose();

                        Thread.Sleep(500);
                        hmiopt.WriteStopVal();
                        //singlemodbus.WriteStopVal();
                        WaitHMIFree();
                        hmiopt.WriteSingleVal();
                        //singlemodbus.WriteSingleVal();

                        textconent.Text = "快速运行...";
                        textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));

                        now_method.Text = "当前运行方法：" + globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.Substring(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.LastIndexOf("\\") + 1);
                    }
                    else
                    {
                        now_method.Text = "当前运行方法：" + "未传输";
                    }
                }
            }            
        }

        string twfilename = null;
        public void startbtn()
        {
            bool ret;
            string tmpFileName;

            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            if (globaldata.connection_ip != null)
            {
                if (tmpFileName != null)
                {
                    twfilename = tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1);
                    twfilename = twfilename.Remove(twfilename.LastIndexOf("."));
                    twfilename += "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".tw";
                    twfilename = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder, twfilename);
                }

                if (twfilename == null)
                {
                    twfilename += "default_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".tw";
                }

                AESfile savefile = new AESfile(twfilename);
                ret = savefile.Create_filetw();

                if (ret)
                {
                    globaldata.startflag = true;
                    globaldata.stopflag = false;
                    globaldata.cancelflag = false;
                    globaldata.startclear = true;
                    globaldata.starttimer = 0;
                    globaldata.startimerIsSet = true;
                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_DataName = twfilename;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 1;
                    //globaldata.work_Statue = 1;

                }
                else
                {
                    MessageBox.Show("创建失败!");
                }
            }

        }

        private void Startbtn_Click(object sender, EventArgs e) //开始
        {        
            
           // if(globaldata.system_Statue == true && globaldata.RunType == 0 )
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
            {
                //this.panelMenu.Controls[0].Enabled = false;
                //int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[0]).Tag);
                //((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[tagnum + 14];

                ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                this.panelMenu.Controls[0].Enabled = false;
                this.panelMenu.Controls[1].Enabled = true;
                ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[1];
                this.panelMenu.Controls[2].Enabled = true;
                ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[2];

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                    //singlemodbus.WriteOpenVal();
                }
                hmiopt.WriteStartVal();
               // singlemodbus.WriteStartVal();

                startbtn();
            }           
        }

        Thread t_checkcmd;
        public void stopbtn()
        {
            globaldata.startflag = false;
            globaldata.stopflag = true;
            globaldata.cancelflag = false;
          //  globaldata.starttimer = 0x7FFFFFFF;
            Console.WriteLine("stopbtn  startimer");
            if (globaldata.connection_ip != null)
            {
               // globaldata.work_Statue = 2;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 2;
            }

            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
            {
                hmiopt.WriteOpenVal();
               // singlemodbus.WriteOpenVal();
               // WaitHMIWork();
                t_checkcmd = new Thread(checkcmd);
                t_checkcmd.IsBackground = true;
                t_checkcmd.Start();

            }
        }

        private void checkcmd()
        {
            while(globaldata.m_hmibuffer.gcinfo.methodstatus != 3)
            {
                if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                }else if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                {
                    hmiopt.WriteSingleVal();
                }else
                {

                }
                Thread.Sleep(1000);
            }

        }


        private void Stopbtn_Click(object sender, EventArgs e)
        {
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
            {
                //int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[0]).Tag);
                //((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[tagnum];

                ((PictureBox)panelMenu.Controls[0]).Enabled = false;
                ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                ((PictureBox)panelMenu.Controls[1]).Enabled = false;
                ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[15];
                ((PictureBox)panelMenu.Controls[2]).Enabled = false;
                ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[16];

                hmiopt.WriteStopVal();
               // singlemodbus.WriteStopVal();
                WaitHMIFree();
             
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                    //singlemodbus.WriteOpenVal();
                }
                stopbtn();
            }                   
        }

        public void cancelbtn()
        {
            globaldata.startflag = false;
            globaldata.stopflag = false;
            globaldata.cancelflag = true;
            globaldata.starttimer = 0x7FFFFFFF;
            Console.WriteLine("cancelbtn  cancelbtn");
            if (globaldata.connection_ip != null)
            {                                      
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 3;               
            }

            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
            {
                hmiopt.WriteOpenVal();
                //singlemodbus.WriteOpenVal();
              //  WaitHMIWork();
                t_checkcmd = new Thread(checkcmd);
                t_checkcmd.IsBackground = true;
                t_checkcmd.Start();
            }
        }

        private void Cancelbtn_Click(object sender, EventArgs e)
        {        
            if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
            {
                //int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[0]).Tag);
                //((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[tagnum];
                ((PictureBox)panelMenu.Controls[0]).Enabled = false;
                ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                ((PictureBox)panelMenu.Controls[1]).Enabled = false;
                ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[15];
                ((PictureBox)panelMenu.Controls[2]).Enabled = false;
                ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[16];

                hmiopt.WriteCancalVal();
               // singlemodbus.WriteCancalVal();
                WaitHMIFree();
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                   // singlemodbus.WriteOpenVal();                   
                }

                cancelbtn();
            }
        }

        void ChangeButton(ushort flag)
        {
            switch(flag)
            {
                case 0:       //关闭所有
                            ((PictureBox)panelMenu.Controls[0]).Enabled = false;
                            ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                            ((PictureBox)panelMenu.Controls[1]).Enabled = false;
                            ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[15];
                            ((PictureBox)panelMenu.Controls[2]).Enabled = false;
                            ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[16];
                            break;
                case 1:       //只使能开始
                            ((PictureBox)panelMenu.Controls[0]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[1]).Enabled = false;
                            ((PictureBox)panelMenu.Controls[2]).Enabled = false;
                            ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[0];                            
                            ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[15];                            
                            ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[16];
                            break;
                case 2:       //使能停止和取消
                            ((PictureBox)panelMenu.Controls[0]).Enabled = false;
                            ((PictureBox)panelMenu.Controls[1]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[2]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                            ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[1];
                            ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[2];
                            break;
                case 3:      //开启所有
                            ((PictureBox)panelMenu.Controls[0]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[1]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[2]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[0];
                            ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[1];
                            ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[2];
                            break;
            }
        }

        void DataControl_Status(ushort flag, ushort runtype)
        {
            switch (flag)
            {
                case 0:
                case 1:
                case 2:
                    //globaldata.work_Statue = 0;
                    
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    break;
                case 3:   //已就绪               
                    break;
                case 4:
                case 5:
                    if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 0)
                        startbtn();
                    break;
                case 6:                  
                case 7:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    break;
            }
        }

        void ButtonControl_Status(ushort flag, ushort runtype)
        {
            invokeDelegate update_ButtonStatus = () =>
            {
                switch(flag)
                {
                    case 0:
                    case 1:
                    case 2:
                        ChangeButton(0);
                        break;
                    case 3:   //已就绪
                        if(runtype == 0 && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue != 1)
                            ChangeButton(1); 
                        break;
                    case 4:
                    case 5:
                        //ChangeButton(2);
                        break;
                    case 6:
                        ChangeButton(0);
                        break;
                    case 7:
                        ChangeButton(0);
                        break;
                }
            };
            Invoke(update_ButtonStatus);
        }

        /// <summary>
        /// 显示系统连接状态和方法运行
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="oldflag"></param>
        void Status_Show(ushort flag, ref ushort oldflag)
        {
            string status_text = null;
            bool color_flag = true;
            switch(flag)
            {
                case 0:
                case 1:
                    status_text = "空闲中...";
                    break;
                case 2:
                    status_text = "仪器平衡中...";
                    break;
                case 3:
                    status_text = "已就绪...";
                    break;
                case 4:
                case 5:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        status_text = "方法运行中...";
                    else if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 2)
                        status_text = "方法运行中...";
                    else if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 3)
                        status_text = "方法运行中...";
                    else
                        status_text = "方法运行中...";
                    break;
                case 6:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    status_text = "后处理...";
                    break;
                case 7:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    status_text = "后处理完毕...";
                    break;
                case 8:
                    status_text = "信号稳定中...";
                    break;
                case 9:
                    status_text = "设备断开";
                    color_flag = false;
                    break;
                default:
                    status_text = "设备连接";
                   
                    break;
            }

            if(oldflag != flag)
            {
                invokeDelegate update_statustext = () =>
                {
                    SetTitleStatueName(status_text, color_flag);
                };
                Invoke(update_statustext);
                oldflag = flag;
            }
        }

        void Common_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            invokeDelegate update_singlerunhead = () =>
            {
                SetMainFormMethodName(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1));
            };
            Invoke(update_singlerunhead);
        }

        void SingleRun_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            invokeDelegate update_singlerunhead = () =>
            {
                SetMainFormMethodName(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1) + " 单次运行");
            };
            Invoke(update_singlerunhead);
        }

        void QuickRun_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            invokeDelegate update_quickrunhead = () =>
            {
                SetMainFormMethodName(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1) + " 快速运行");
            };
            Invoke(update_quickrunhead);
        }

        void BAT_HeadInfo(ushort num, ushort count)
        {        
            INIOperation runtable = new INIOperation(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab);
            string[] key = runtable.INIGetAllItemKeys("运行表");
            string[] runnum = runtable.INIGetAllItemKeys("循环");

            if (num < key.Length)
            {
                if ((num != 0 || count > 0))
                {
                    if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue != 0)
                    {
                        invokeDelegate update_methodname = () =>
                        {
                            SetMainFormMethodName(runtable.INIGetStringValue("运行表", key[num], "无") + "  批处理： " + " 第" + (count + 1).ToString() + "/" + runtable.INIGetStringValue("循环", runnum[num], "无") + "次");
                        };
                        Invoke(update_methodname);
                    }
                    else
                    {
                        invokeDelegate update_methodname = () =>
                        {
                            SetMainFormMethodName(runtable.INIGetStringValue("运行表", key[num], "无") + "  批处理 ");
                        };
                        Invoke(update_methodname);
                    }
                    
            
                    
                }
            }
        }

      
        private void showdata_Click(object sender, EventArgs e)
        {
            if (queryprocess.IsDisposed)
            {
                queryprocess = new WaveTotalForm();
                queryprocess.Show();
            }
            else
            {
                queryprocess.Show();
            }
        }
 private void sfruntimer_Tick(object sender, EventArgs e)
        {
            endTime = System.DateTime.Now;
            time = endTime - startTime;
            ((Label)((Panel)this.panelMenu.Controls[10]).Controls[1]).Text =time.Days.ToString() + "D " + time.Hours.ToString() + ":"+ time.Minutes.ToString() + ":"+ time.Seconds.ToString();
        }

    }
}
