关闭

C# 系统分析器(第一个C#程序)

标签: c#stringobjectexceptionnullsystem
3936人阅读 评论(2) 收藏 举报

代码太多了,我现在不能上传附件下次再传吧!

frmMain.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Management;
using Microsoft.Win32;

namespace ProcessManager
{
    public partial class frmMain : Form
    {
        //构造函数
        public frmMain()
        {
            InitializeComponent();
            //设置在多线程的时候开启2003的模式
            CheckForIllegalCrossThreadCalls = false;
        }
        private string sProcessName;
        private string sProcessId;
        private string sProcessOwner;
        private string scpu;
        private string sWorkingSet;
        private string sFilePath;
        private string sPriority;
        private string sMainWindowTitle;

        private delegate bool CallBack(int hwnd, int lParam);
        [DllImport("user32")]
        private static extern int EnumWindows(CallBack xlpEnumFunc, int lParam);
        [DllImport("user32")]
        private static extern int GetWindowThreadProcessId(int hwnd, ref int lpdwProcessId);
        [DllImport("user32")]
        private static extern bool IsWindowVisible(int hwnd);
        [DllImport("user32")]
        private static extern int EnableWindow(int hwnd, int fEnable);
        [DllImport("user32")]
        private static extern int ShowWindow(int hwnd, int nCmdShow);
        [DllImport("user32")]
        private static extern int GetWindowText(int hwnd, StringBuilder lpString, int cch);
        [DllImport("user32")]
        private static extern int GetWindowTextLength(int hwnd);
        [DllImport("user32")]
        private static extern int IsWindowEnabled(int hwnd);
        [System.Runtime.InteropServices.DllImport("shell32")]
        private static extern IntPtr ExtractAssociatedIcon(IntPtr hInst, string lpIconPath, ref int lpiIcon);
        [System.Runtime.InteropServices.DllImport("user32")]
        private static extern int RegisterWindowMessage(string lpString);
        [System.Runtime.InteropServices.DllImport("user32")]
        private static extern int RegisterShellHookWindow(int Hwnd);
        [System.Runtime.InteropServices.DllImport("shell32",EntryPoint="#181")]
        private static extern int RegisterShellHook(int Hwnd, int nAction);
       
        private static IntPtr hIcon;
        private static IntPtr hIcons;
        private int msgShellHook;
        [DllImport("user32")]
        private static extern int PostMessage(int hwnd, int wMsg, int wParam, ref int lParam);
        //[DllImport("user32")]
        //private static extern int SendMessage(int hwnd, int wMsg, int wParam, ref int lParam);
        [DllImport("shell32")]
        private static extern int ShellExecute(int hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);
        private const int WM_CLOSE = 0x10;
        private const int SC_MINIMIZE = 0xF020;
        private const int WM_SYSCOMMAND = 0x112;
        private const int WM_HOTKEY = 0x312;
        //private const int MOD_CTRL = 0x2;
        //private const int MOD_SHFT = 0x4;
        //private const int MOD_ALT = 0x1;
        private enum KeyModifiers
        {
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8
        }
        [DllImport("user32")]
        private static extern int RegisterHotKey(IntPtr hwnd, int ID, KeyModifiers fsModifiers, Keys vk);
        [DllImport("user32")]
        private static extern int UnregisterHotKey(IntPtr hwnd, int ID);

        //端口处理类
        private portInfo myportInfo = new portInfo();
        private win32servicemanager servicemanager = new win32servicemanager(".", null, null);
        //监视进程创建事件
        private ManagementEventWatcher Create;
        //监视进程结束事件
        private ManagementEventWatcher Delete;
        private bool isShowHideWindow = false;
        private bool isRunning = false;

        private void frmMain_Load(object sender, EventArgs e)
        {
            Size mySize = new Size(588, 433);
            this.MinimumSize = mySize;
            tray.Visible = true;
            this.Icon = tray.Icon;
            this.MinimizeBox = false;
            RegisterHotKey(this.Handle, 0, KeyModifiers.Control | KeyModifiers.Alt, Keys.Insert);
            //string[] keys;
            //keys = Registry.LocalMachine.OpenSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//run").GetValueNames();
            //foreach (string a in keys)
            //{
            //    MessageBox.Show(Registry.GetValue("HKEY_LOCAL_MACHINE//SOFTWARE//Microsoft//Windows//CurrentVersion//Run",a,"").ToString());
            //}
            //EnablePrivileges myEnablePrivileges = new EnablePrivileges();
            //myEnablePrivileges.EnablePrivilege();
            this.tray.MouseDoubleClick +=new MouseEventHandler(tray_MouseDoubleClick);
            this.FormClosing += new FormClosingEventHandler(frmMain_FormClosing);
            startProcessEvent("__instancecreationevent");
            startProcessEvent("__InstanceDeletionEvent");
            this.lstView.MouseUp += new MouseEventHandler(lstView_MouseUp);
            this.tabs.SelectedIndexChanged += new EventHandler(this.tabs_SelectedIndexChanged);
            this.lsvService.Click += new EventHandler(this.lsvService_Click);
            this.lsvService.KeyUp += new KeyEventHandler(this.lsvService_KeyUp);
            this.proLstView.MouseUp += new MouseEventHandler(this.proLstView_MouseUp);
            this.proLstView.ColumnClick += new ColumnClickEventHandler(this.proLstView_ColumnClick);
            this.lsvService.MouseUp +=new MouseEventHandler(lsvService_MouseUp);
            //this.ResizeBegin += new EventHandler(frmMain_ResizeBegin);
            this.Resize += new EventHandler(frmMain_Resize);
            //this.ResizeEnd +=new EventHandler(frmMain_ResizeEnd);
            this.Show();
            setTabs();
            CallBack myCallBack = new CallBack(EnumWindowsProc);
            EnumWindows(myCallBack, 0);
            //if (ConnectProcessServer(".", null, null))
            //{
            //    GetProcessList();
            //}
            //wTimer.Enabled = true;
            //wTimer.Start();
            GetProcessList();
            msgShellHook = RegisterWindowMessage("SHELLHOOK");
            //RegisterShellHookWindow(this.Handle.ToInt32());
            RegisterShellHook(this.Handle.ToInt32(), 1 | 2 | 3);
            this.MinimizeBox = true;
            this.tray.MouseMove += new MouseEventHandler(tray_MouseMove);
            proLstView.Sort();
            //this.lsvService.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(this.lsvService_ItemSelectionChanged);
            this.proLstView.DoubleClick += new System.EventHandler(this.proLstView_DoubleClick);
            //this.tabs.SelectTab(1);
        }

        protected override void WndProc(ref Message m)
        {
            if ((m.Msg == WM_SYSCOMMAND) && (m.WParam.ToInt32() == SC_MINIMIZE))
            {
                tray.Visible = true;
                this.Icon = tray.Icon;
                this.Hide();
            }
            else if (m.Msg == WM_HOTKEY)
            {
                HotKeyMsg(m.WParam.ToInt32());
            }
            else if (m.Msg == msgShellHook)
            {
                switch (m.WParam.ToInt32())
                {
                    case 1:
                        int pid=0;
                        if (GetWindowThreadProcessId(m.LParam.ToInt32(),ref pid) != 0)
                        {
                            Process myProcess = Process.GetProcessById(pid);
                            ListViewItem lv = new ListViewItem();
                            StringBuilder strCaption = new StringBuilder(260);
                            GetWindowText(m.LParam.ToInt32(), strCaption, sizeof(strCaption));
                            lv = lstView.Items.Add(strCaption.ToString());
                            //lv=lstView.Items.Add(myProcess.MainWindowTitle);
                            int IconIndex = 0;
                            try
                            {
                           
                                hIcon = ExtractAssociatedIcon(this.Handle, myProcess.MainModule.FileName.ToString(), ref IconIndex);
                                Icon icon = Icon.FromHandle(hIcon);
                                sImageLst.Images.Add(icon);
                                lstView.Items[lstView.Items.Count - 1].ImageIndex = sImageLst.Images.Count - 1;
                            }
                            catch { }
                            lv.SubItems.AddRange(new string[]{pid.ToString(),m.LParam.ToString(),myProcess.MainModule.FileName,myProcess.Responding?"正在运行":"没有响应"});
                        }
                        break;
                    case 2:
                        ListViewItem lsv = lstView.FindItemWithText(m.LParam.ToString());
                        try
                        {
                            lstView.Items.Remove(lsv);
                        }
                        catch { }
                        break;
                }
            }
            else
            {
                base.WndProc(ref m);
            }
        }

        private void HotKeyMsg(int msgId)
        {
            this.Show();
        }

        private void proLstView_ColumnClick(object o, ColumnClickEventArgs e)
        {
            this.proLstView.ListViewItemSorter = new ListViewItemComparer(e.Column);
        }


        private void tray_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            this.Show();
            this.Activate();
        }

        private void tray_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (this.Visible == false)
                {
                    tray.ContextMenuStrip = trayMenu;
                }
                else
                {
                    tray.ContextMenuStrip = null;
                }
            }
           
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {
            if (this.Width < 588)
            {
                this.Width = 588;
            }
            else
            {
                this.tabs.Width=this.Width-20;
                try
                {
                    this.tabs.TabPages[tabs.SelectedIndex].Controls[0].Width = this.Width - 29;
                }
                catch { }
            }
            if (this.Height < 433)
            {
                this.Height = 433;
            }
            else
            {
                this.tabs.Height = this.Height - 77;
                try
                {
                    this.tabs.TabPages[tabs.SelectedIndex].Controls[0].Height = this.Height - 109;
                }
                catch { }
            }
            if (this.Height != 433 || this.Width != 588)
            {
                cmdExit.Location = new Point(this.Width - 88, this.Height - 63);
                cmdKillService.Location = new Point(cmdExit.Location.X - 80, cmdExit.Location.Y);
                cmdStop.Location = new Point(cmdKillService.Location.X - 80, cmdExit.Location.Y);
                cmdPause.Location = new Point(cmdStop.Location.X - 80, cmdExit.Location.Y);
                cmdRunService.Location = new Point(cmdPause.Location.X - 80, cmdExit.Location.Y);
            }
            else
            {
                cmdExit.Location = new Point(500, 370);
                cmdKillService.Location = new Point(420, 370);
                cmdStop.Location = new Point(340, 370);
                cmdPause.Location = new Point(260, 370);
                cmdRunService.Location = new Point(180, 370);

            }
            //ListView lv=(ListView)this.tabs.TabPages[tabs.SelectedIndex].Controls[0];
            //int max = 0;
            //if (lv.Items.Count>0)
            //{
            //    ListViewItem item=lv.Items[0];
            //    max=(int)this.CreateGraphics().MeasureString(item.SubItems[0].Text,this.Font).Width;
            //    for (int i = 0; i < item.SubItems.Count; i++)
            //    {
            //        for (int j = 1; j < lv.Items.Count - 1; j++)
            //        {
            //            if ((int)this.CreateGraphics().MeasureString(lv.Items[j].SubItems[i].Text, this.Font).Width > max)
            //            {
            //                max = (int)this.CreateGraphics().MeasureString(lv.Items[j].SubItems[i].Text, this.Font).Width;
            //            }
            //        }
            //        lv.Columns[i].Width = max + 10;
            //        max = (int)this.CreateGraphics().MeasureString(item.SubItems[0].Text,this.Font).Width;
            //    }
            //}

        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.tray.MouseDoubleClick -= new MouseEventHandler(tray_MouseDoubleClick);
            this.lstView.MouseUp -= new MouseEventHandler(lstView_MouseUp);
            this.tabs.SelectedIndexChanged -= new EventHandler(this.tabs_SelectedIndexChanged);
            this.lsvService.Click -= new EventHandler(this.lsvService_Click);
            this.lsvService.KeyUp -= new KeyEventHandler(this.lsvService_KeyUp);
            this.proLstView.MouseUp -= new MouseEventHandler(this.proLstView_MouseUp);
            this.proLstView.ColumnClick -= new ColumnClickEventHandler(this.proLstView_ColumnClick);
            this.lsvService.MouseUp -= new MouseEventHandler(lsvService_MouseUp);
            Create.Stop();
            Delete.Stop();
            UnregisterHotKey(this.Handle, 0);
        }

        private void startProcessEvent(string className)
        {
            ConnectionOptions co = new ConnectionOptions();
            co.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope scope = new ManagementScope("////.//root//cimv2", co);
            WqlEventQuery wql = new WqlEventQuery(className, new TimeSpan(0, 0, 1), "TargetInstance ISA 'Win32_Process'");
            if (className == "__instancecreationevent")
            {
                Create = new ManagementEventWatcher(scope, wql);
                Create.EventArrived += new EventArrivedEventHandler(ProcessCreate_Event);
                Create.Start();
            }
            else
            {
                Delete = new ManagementEventWatcher(scope, wql);
                Delete.EventArrived += new EventArrivedEventHandler(ProcessDelete_Event);
                Delete.Start();
            }
        }

        private void ProcessCreate_Event(Object sender, EventArrivedEventArgs e)
        {
           
            ManagementBaseObject mo = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
            this.sProcessName = mo["Name"].ToString();
            this.sProcessId = mo["ProcessId"].ToString();
            this.sProcessOwner = GetProcessOwner(mo["ProcessId"].ToString());
            this.scpu = "";
            this.sWorkingSet = Convert.ToString((Convert.ToInt32(mo["WorkingSetSize"]) / 1024)) + "K";
            this.sFilePath = mo["CommandLine"].ToString().Replace("/"", "");
            this.sPriority = ConvertPriorityToString(Convert.ToInt32(mo["Priority"]));
            this.sMainWindowTitle = Process.GetProcessById(Convert.ToInt32(mo["ProcessId"])).MainWindowTitle;
            //AddToListview myAddToListview = new AddToListview(mo["Name"].ToString(), mo["ProcessId"].ToString(), GetProcessOwner(mo["ProcessId"].ToString()), "", Convert.ToString((Convert.ToInt32(mo["WorkingSetSize"]) / 1024)) + "K", mo["CommandLine"].ToString().Replace("/"", ""), mo["Priority"].ToString(), Process.GetProcessById(Convert.ToInt32(mo["ProcessId"])).MainWindowTitle);
            Thread myThread = new Thread(new ThreadStart(addProcessListView));
            myThread.Start();
        }

        private void ProcessDelete_Event(Object sender, EventArrivedEventArgs e)
        {
            ManagementBaseObject mo = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
            try
            {
                this.sProcessId = mo["ProcessId"].ToString();
                //AddToListview myAddToListview = new AddToListview(mo["Name"].ToString(), mo["ProcessId"].ToString(), GetProcessOwner(mo["ProcessId"].ToString()), "", Convert.ToString((Convert.ToInt32(mo["WorkingSetSize"]) / 1024)) + "K", mo["CommandLine"].ToString().Replace("/"", ""), mo["Priority"].ToString(), Process.GetProcessById(Convert.ToInt32(mo["ProcessId"])).MainWindowTitle);
                Thread myThread = new Thread(new ThreadStart(RemoveListViewItem));
                myThread.Start();
            }
            catch { }
        }

        private void RemoveListViewItem()
        {
            try
            {
                proLstView.Items.Remove(proLstView.FindItemWithText(this.sProcessId));
            }
            catch { }
        }

        private void addProcessListView()
        {
            ListViewItem lsv = new ListViewItem();
            lsv = proLstView.Items.Add(sProcessName);
            int IconIndex = 0;
            try
            {
                hIcons = ExtractAssociatedIcon(this.Handle, this.sFilePath, ref IconIndex);
                Icon icons = Icon.FromHandle(hIcons);
                processImgLst.Images.Add(icons);
                proLstView.Items[proLstView.Items.Count - 1].ImageIndex = processImgLst.Images.Count - 1;
            }
            catch { }
            lsv.SubItems.AddRange(new string[] { sProcessId, sProcessOwner, scpu, sWorkingSet, sFilePath, sPriority, sMainWindowTitle });
        }

        private bool EnumWindowsProc(int hwnd, int lParam)
        {
            int windowLength = 0;
            int pid = 0;

            //if (IsWindowVisible(hwnd))
            //{
                windowLength = GetWindowTextLength(hwnd);
                if (windowLength > 0 && IsWindowEnabled(hwnd) > 0)
                {
                    Application.DoEvents();
                    GetWindowThreadProcessId(hwnd, ref pid);
                    Process myProcess = Process.GetProcessById(pid);
                    StringBuilder caption = new StringBuilder(windowLength);
                    GetWindowText(hwnd, caption, windowLength + 1);
                    if (caption.ToString().ToLower() == "program manager") return false;
                    ListViewItem lv = new ListViewItem();
                    if ((isShowHideWindow == false && IsWindowVisible(hwnd)) || isShowHideWindow == true)
                    {
                        //if (lstView.FindItemWithText(caption.ToString())==null)
                        lv = lstView.Items.Add(caption.ToString());
                        int IconIndex = 0;
                        try
                        {
                            if (myProcess.MainModule.FileName.ToString().ToLower()==System.IO.Path.GetDirectoryName(System.Environment.GetFolderPath(Environment.SpecialFolder.System)).ToLower() + "//explorer.exe") IconIndex = 13;
                            hIcon = ExtractAssociatedIcon(this.Handle, myProcess.MainModule.FileName.ToString(), ref IconIndex);
                            Icon icon = Icon.FromHandle(hIcon);
                            //this.Icon = icon;
                            sImageLst.Images.Add(icon);
                            lstView.Items[lstView.Items.Count - 1].ImageIndex = sImageLst.Images.Count - 1;
                        }
                        catch { }
                    }

                    string runFlag;
                    if (myProcess.Responding)
                    {
                        runFlag = "正在运行";
                    }
                    else
                    {
                        runFlag = "没有响应";
                    }
                    try
                    {
                        if ((isShowHideWindow == false && IsWindowVisible(hwnd)) || isShowHideWindow == true) lv.SubItems.AddRange(new string[] { pid.ToString(), hwnd.ToString(), myProcess.MainModule.FileName.ToString(), runFlag });
                        if (IsWindowVisible(hwnd) == false && isShowHideWindow == true) lv.ForeColor = System.Drawing.Color.Red;
                    }
                    catch
                    {
                        if ((isShowHideWindow == false && IsWindowVisible(hwnd)) || isShowHideWindow == true) lv.SubItems.AddRange(new string[] { pid.ToString(), hwnd.ToString(), "", runFlag });
                        if (IsWindowVisible(hwnd)==true && isShowHideWindow == true) lv.ForeColor = System.Drawing.Color.Red;
                    }
                    //myProcess.EnableRaisingEvents = true;
                    //myProcess.Exited += new EventHandler(myProcess_Exited);
                //}
            }
            return true;
        }

        //获取进程列表
        private void GetProcessList()
        {
            Process[] myProcesses = Process.GetProcesses();
            foreach (Process myProcess in myProcesses)
            {
                Application.DoEvents();
                ListViewItem lsv = new ListViewItem();
                if (myProcess.ProcessName == "System")
                {
                    lsv = proLstView.Items.Add(myProcess.ProcessName);
                    lsv.SubItems.AddRange(new string[] { myProcess.Id.ToString(), "SYSTEM", "", Convert.ToString(myProcess.WorkingSet64 / 1024) + "K", "", ConvertPriorityToString(myProcess.PriorityClass), "" });
                }
                else if (myProcess.ProcessName == "Idle")
                {
                    lsv = proLstView.Items.Add(myProcess.ProcessName);
                    lsv.SubItems.AddRange(new string[] { myProcess.Id.ToString(), "SYSTEM", "", Convert.ToString(myProcess.WorkingSet64 / 1024) + "K", "", "", "" });
                }
                else
                {
                    lsv = proLstView.Items.Add(myProcess.ProcessName);
                    int IconIndex = 0;
                    try
                    {
                        if (myProcess.ProcessName.ToLower() == "csrss" || myProcess.ProcessName.ToLower() == "winlogon")
                        {
                            hIcons = ExtractAssociatedIcon(this.Handle, myProcess.MainModule.FileName.ToString().Substring(4), ref IconIndex);
                        }
                        else hIcons = ExtractAssociatedIcon(this.Handle, myProcess.MainModule.FileName.ToString(), ref IconIndex);
                        Icon icons = Icon.FromHandle(hIcons);
                        processImgLst.Images.Add(icons);
                        proLstView.Items[proLstView.Items.Count - 1].ImageIndex = processImgLst.Images.Count - 1;
                    }
                    catch { }

                    string ProcessUser = "";
                    ProcessUser = GetProcessOwner(myProcess.Id.ToString());
                    try
                    {
                        lsv.SubItems.AddRange(new string[] { myProcess.Id.ToString(), ProcessUser, "", Convert.ToString(myProcess.WorkingSet64 / 1024) + "K", myProcess.MainModule.FileName, ConvertPriorityToString(myProcess.PriorityClass), myProcess.MainWindowTitle });
                    }
                    catch { lsv.SubItems.AddRange(new string[] { myProcess.Id.ToString(), "", "", Convert.ToString(myProcess.WorkingSet64 / 1024) + "K", "", "", myProcess.MainWindowTitle }); }

                }
            }
        }


        private string GetProcessOwner(string processId)
        {
            string queryString = "Select * From Win32_Process Where ProcessID = " + processId;
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(queryString);
            ManagementObjectCollection processList = searcher.Get();
            string owner = string.Empty;
            foreach (ManagementObject currentProcess in processList)
            {
                string[] argList = { string.Empty };
                int returnValue = Convert.ToInt32(currentProcess.InvokeMethod("GetOwner", argList));
                if (returnValue == 0) owner = argList[0];
            }
            return owner;
        }

        private void wTimer_Tick(object sender, EventArgs e)
        {
            sImageLst.Images.Clear();
            lstView.Items.Clear();
            CallBack myCallBack = new CallBack(EnumWindowsProc);
            EnumWindows(myCallBack, 0);
        }

        private string getCpuPercent(Process myProcess)
        {
            Process[] myProcesses = Process.GetProcesses();
            double m = 0;

            foreach (Process p in myProcesses)
            {
                if (p.ProcessName == "System")
                {
                    m += p.UserProcessorTime.TotalSeconds;
                    m += p.UserProcessorTime.TotalMinutes * 60;
                    m += p.UserProcessorTime.TotalHours * 3600;
                }
                else if (p.ProcessName == "Idle")
                {
                    m += p.TotalProcessorTime.TotalSeconds;
                    m += p.TotalProcessorTime.TotalMinutes * 60;
                    m += p.TotalProcessorTime.TotalHours * 3600;
                    //MessageBox.Show(myProcess.UserProcessorTime.TotalMinutes.ToString());
                }
                else
                {
                    m += p.UserProcessorTime.TotalSeconds;
                    m += p.UserProcessorTime.TotalMinutes * 60;
                    m += p.UserProcessorTime.TotalHours * 3600;
                }
            }
            double dCurrent=0;
            dCurrent = myProcess.UserProcessorTime.TotalSeconds;
            dCurrent = myProcess.UserProcessorTime.TotalMinutes * 60;
            dCurrent = myProcess.UserProcessorTime.TotalHours * 3600;
            MessageBox.Show(m.ToString() + " " + dCurrent.ToString());
            return Convert.ToString((dCurrent / m));
        }

        private void ShowServicesList()
        {
            if (servicemanager.remoteconnectvalidate(".", null, null))
            {
                isRunning = true;
                string[,] services = servicemanager.getservicelist();
                this.lsvService.Items.Clear();
                this.lsvService.BeginUpdate();             
                for (int i = 0; i < services.GetLength(0); i++)
                {
                    string flag = "";
                    string runFlag = "";
                    Application.DoEvents();
                    switch (services[i, 3])
                    {
                        case "Running":
                            flag = "已启动";
                            break;
                        case "Stopped":
                            flag = "已停止";
                            break;
                        case "Paused":
                            flag = "已暂停";
                            break;
                    }

                    switch (services[i, 4])
                    {
                        case "Auto":
                            runFlag = "自动";
                            break;
                        case "Manual":
                            runFlag = "手动";
                            break;
                        case "Disabled":
                            runFlag = "已禁用";
                            break;
                    }
                    string sStartName = null;
                    if (services[i, 6] == "LocalSystem")
                    {
                        sStartName = "本地系统";
                    }
                    else if (services[i, 6] == "NT AUTHORITY//LocalService")
                    {
                        sStartName = "本地服务";
                    }
                    else sStartName = "网络服务";
                    ListViewItem item = new ListViewItem(new string[] { services[i, 0], services[i, 1], services[i, 2], flag, runFlag, services[i, 5], sStartName });
                    if (flag == "已停止")
                    {
                        item.ForeColor = System.Drawing.Color.Red;
                    }
                    else if (flag == "已暂停")
                    {
                        item.ForeColor = System.Drawing.Color.Blue;
                    }
                    this.lsvService.Items.Add(item);
                }
                this.lsvService.EndUpdate();
                lsvService.Items[0].Selected = true;
                lsvService.Items[0].Focused = true;
                lsvService.Focus();
                lsvService_Click((object)lsvService.Items[0],new EventArgs());
                lsvService.Refresh();
                isRunning = false;
            }
        }

        private void proLstView_DoubleClick(object sender, EventArgs e)
        {
            int pid = 0;
            pid=Convert.ToInt32(proLstView.SelectedItems[proLstView.SelectedIndices.Count - 1].SubItems[1].Text);
            Process myProcess = Process.GetProcessById(pid);
            ProcessManager.processModule prom = new ProcessManager.processModule();
            try
            {
                ProcessModuleCollection myProcessModuleCollection = myProcess.Modules;
                foreach (ProcessModule myProcessModule in myProcessModuleCollection)
                {
                    ListViewItem lv = new ListViewItem();
                    lv = prom.lsvProcessModule.Items.Add(myProcessModule.BaseAddress.ToString());
                    lv.SubItems.AddRange(new string[] { myProcessModule.FileName });
                }
                prom.lPID.Text = "进程PID:" + pid.ToString();
                prom.lModuleCount.Text = "共计:" + myProcessModuleCollection.Count.ToString();
            }
            catch { }
            if (prom.lsvProcessModule.Items.Count >= 19)
            {
                prom.lsvProcessModule.Columns[1].Width = prom.lsvProcessModule.Columns[1].Width - 7;
            }
            else prom.lsvProcessModule.Columns[1].Width = prom.lsvProcessModule.Columns[1].Width + 10;
            prom.ShowDialog();
        }

        private void cmdRunService_Click(object sender, EventArgs e)
        {
            if (cmdRunService.Text == "启动(&R)")
            {
                if (lsvService.SelectedItems.Count == 0)
                {
                    MessageBox.Show("你还没有选择需要启动的服务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                string msg;
                int n;
                n = lsvService.SelectedIndices.Count - 1;
                if (lsvService.SelectedItems[n].SubItems[4].Text == "已禁用")
                {
                    servicemanager.setServiceValue(lsvService.SelectedItems[n].SubItems[0].Text, "Auto");
                }
                msg = servicemanager.startservice(lsvService.SelectedItems[n].SubItems[0].Text);
                if (msg == null)
                {
                    MessageBox.Show("启动服务成功!!");
                    lsvService.SelectedItems[n].SubItems[3].Text = "已启动";
                    lsvService.SelectedItems[n].ForeColor = System.Drawing.Color.Black;
                    cmdRunService.Enabled = false;
                    cmdPause.Enabled = true;
                    cmdStop.Enabled = true;
                }
                else
                {
                    MessageBox.Show(msg);
                }
                lsvService.Items[n].Focused = true;
                lsvService.Focus();
            }
            else if (cmdRunService.Text == "删除文件")
            {
                delProcessFiles();
            }
            else if (cmdRunService.Text == "所有窗体")
            {
                isShowHideWindow = true;
                cmdRunService.Text = "正常窗体";
                wTimer_Tick(new object(), new EventArgs());
            }

            else if (cmdRunService.Text == "正常窗体")
            {
                isShowHideWindow = false;
                cmdRunService.Text = "所有窗体";
                wTimer_Tick(new object(), new EventArgs());
            }
            else if (cmdRunService.Text == "按本地IP")
            {
                shutLocaPort_Click(new object(), new EventArgs());
            }
            else if (cmdRunService.Text == "添加(&I)")
            {
                RunRegAdd myRunRegAdd = new RunRegAdd(lsvRun);
                myRunRegAdd.Show();
            }
        }
       
        private void lsvService_Click(object sender, EventArgs e)
        {

            if (lsvService.Items.Count == 0) return;
            if (lsvService.SelectedItems[0].SubItems[3].Text == "已启动")
            {
                cmdRunService.Enabled = false;
                if (servicemanager.GetServicePauseFlag(lsvService.SelectedItems[0].SubItems[0].Text))
                {
                    cmdPause.Enabled = true;
                }
                else cmdPause.Enabled = false;
                cmdStop.Enabled = true;
            }
            else if (lsvService.SelectedItems[0].SubItems[3].Text == "已暂停")
            {
                cmdPause.Enabled = true;
                cmdPause.Text = "恢复(&R)";
                cmdStop.Enabled = true;
                cmdRunService.Enabled = false;
            }
            else
            {
                cmdRunService.Enabled = true;
                if (servicemanager.getservicevalue(lsvService.SelectedItems[0].SubItems[0].Text, "state").ToString().ToLower() == "running")
                {
                    cmdPause.Enabled = true;
                }
                else cmdPause.Enabled = false;
                cmdStop.Enabled = false;
            }

            if (lsvService.SelectedItems[0].SubItems[1].Text != "0")
            {
                cmdKillService.Enabled = true;
            }
            else cmdKillService.Enabled = false;
        }

        private void cmdStop_Click(object sender, EventArgs e)
        {
            if (cmdStop.Text=="停止(&S)")
            {
                if (lsvService.SelectedItems.Count == 0)
                {
                    MessageBox.Show("你还没有选择需要停止的服务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                string msg=null;
                int n;
                n = lsvService.SelectedIndices.Count - 1;
                msg = servicemanager.stopservice(lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].SubItems[0].Text);
                if (msg == null)
                {
                    MessageBox.Show("停止服务成功!!");
                    lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].SubItems[1].Text = "0";
                    lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].SubItems[3].Text = "已停止";
                    lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].ForeColor = System.Drawing.Color.Red;
                    cmdRunService.Enabled = true;
                    cmdPause.Enabled = false;
                    cmdStop.Enabled = false;
                }
                else
                {
                    MessageBox.Show(msg);
                }
                lsvService.Items[n].Focused = true;
                lsvService.Focus();
            }
            else if (cmdStop.Text == "关闭窗体")
            {
                shutWindow();
            }
            else if (cmdStop.Text == "模块")
            {
                if (proLstView.SelectedItems.Count == 0)
                {
                    MessageBox.Show("你还没有选定需要察看的进程!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                int n = 0;
                n = proLstView.SelectedIndices.Count - 1;
                proLstView_DoubleClick(new object(), new EventArgs());
                proLstView.Items[n].Focused = true;
                proLstView.Focus();
            }
            else if (cmdStop.Text == "按本地端口")
            {
                shutPortLoca_Click(new object(), new EventArgs());
            }
            else if (cmdStop.Text == "启用(&S)")
            {
                foreach (ListViewItem item in lsvRun.Items)
                {
                    if (item.Checked == true)
                    {
                        Registry.SetValue(item.SubItems[2].Text, item.SubItems[0].Text, item.SubItems[1].Text);
                    }
                    else
                    {
                        string shellRegPath="HKEY_LOCAL_MACHINE//SOFTWARE//Microsoft//Windows NT//CurrentVersion//Winlogon".ToLower();
                        string userLoadPath = "HKEY_CURRENT_USER//SOFTWARE//Microsoft//Windows NT//CurrentVersion//Windows".ToLower();
                        string locaPath = "HKEY_LOCAL_MACHINE";
                        string userPath = "HKEY_CURRENT_USER";
                        if (item.SubItems[2].Text.Substring(0, item.SubItems[2].Text.IndexOf('//')) == locaPath)
                        {
                            if (item.SubItems[2].Text.ToLower() == shellRegPath)
                            {
                                if (item.SubItems[0].Text.ToLower() == "shell")
                                {
                                    Registry.SetValue(shellRegPath, "shell", "Explorer.exe");
                                }
                                else if (item.SubItems[0].Text.ToLower() == "system")
                                {
                                    Registry.SetValue(shellRegPath, "System", "");
                                }
                                else if (item.SubItems[0].Text.ToLower() == "userinit")
                                {
                                    Registry.SetValue(shellRegPath, "Userinit", System.Environment.SystemDirectory + "//Userinit.exe,");
                                }
                            }
                            else
                            {
                                RegistryKey myRegistryKey = Registry.LocalMachine.CreateSubKey(item.SubItems[2].Text.Substring(item.SubItems[2].Text.IndexOf('//') + 1, item.SubItems[2].Text.Length - item.SubItems[2].Text.IndexOf('//') - 1));
                                myRegistryKey.DeleteValue(item.SubItems[0].Text, false);
                            }

                        }
                        else if (item.SubItems[2].Text.Substring(0, item.SubItems[2].Text.IndexOf('//')) == userPath)
                        {
                            if (item.SubItems[2].Text.ToLower() == userLoadPath)
                            {
                                if (item.SubItems[0].Text.ToLower() == "run")
                                {
                                    Registry.SetValue(userLoadPath, "run", "");
                                }
                                else if (item.SubItems[0].Text.ToLower() == "load")
                                {
                                    Registry.SetValue(userLoadPath, "load", "");
                                }
                            }
                            else
                            {
                                RegistryKey myRegistryKey = Registry.CurrentUser.CreateSubKey(item.SubItems[2].Text.Substring(item.SubItems[2].Text.IndexOf('//') + 1, item.SubItems[2].Text.Length - item.SubItems[2].Text.IndexOf('//') - 1));
                                myRegistryKey.DeleteValue(item.SubItems[0].Text, false);
                            }
                        }
                        item.Remove();
                    }
                }
            }
        }

        private void shutWindow()
        {
            if (this.lstView.SelectedItems.Count == 0)
            {
                MessageBox.Show("你还没有选定需要关闭的窗体!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int tt = 0;
            PostMessage(Convert.ToInt32(lstView.SelectedItems[0].SubItems[2].Text), WM_CLOSE, 0, ref tt);
            Thread.Sleep(100);
            wTimer_Tick(new object(), new EventArgs());
        }

        private void cmdPause_Click(object sender, EventArgs e)
        {
            if ((cmdPause.Text == "暂停(&P)") || (cmdPause.Text == "恢复(&R)"))
            {
                if (lsvService.SelectedItems.Count == 0)
                {
                    MessageBox.Show("你还没有选择需要暂停/恢复的服务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                string msg=null;
                int n=0;
                n = lsvService.SelectedIndices.Count - 1;
           
                if (cmdPause.Text == "暂停(&P)")
                {
                    msg = servicemanager.pauseservice(lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].SubItems[0].Text);
                    if (msg == null)
                    {
                        MessageBox.Show("暂停服务成功!!");
                        lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].SubItems[3].Text = "已暂停";
                        lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].ForeColor = System.Drawing.Color.Blue;
                        cmdRunService.Enabled = false;
                        cmdPause.Enabled = true;
                        cmdStop.Enabled = true;
                        cmdPause.Text = "恢复(&R)";
                        lsvService.Items[n].Focused = true;
                        lsvService.Focus();
                    }
                    else
                    {
                        MessageBox.Show(msg);
                        lsvService.Items[n].Focused = true;
                        lsvService.Focus();
                    }
                }
                else if (cmdPause.Text == "恢复(&R)")
                {
                    msg = servicemanager.resumeservice(lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].SubItems[0].Text);
                    if (msg == null)
                    {
                        MessageBox.Show("恢复服务成功!!");
                        lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].SubItems[3].Text = "已启动";
                        lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].ForeColor = System.Drawing.Color.Black;
                        cmdRunService.Enabled = false;
                        cmdPause.Enabled = true;
                        cmdStop.Enabled = true;
                        cmdPause.Text = "暂停(&P)";
                        lsvService.Items[n].Focused = true;
                        lsvService.Focus();
                    }
                    else
                    {
                        MessageBox.Show(msg);
                        lsvService.Items[n].Focused = true;
                        lsvService.Focus();
                    }
                }
            }
            if (cmdPause.Text == "刷新")
            {
                if (tabs.SelectedIndex == 0)
                {
                    wTimer_Tick(new object(), new EventArgs());
                }
                else if (tabs.SelectedIndex == 1)
                {
                    proLstView.Items.Clear();
                    GetProcessList();
                }
            }

            if (cmdPause.Text == "按远程IP")
            {
                shutRemovePort_Click(new object(), new EventArgs());
            }

            if (cmdPause.Text == "刷新(&R)")
            {
                lsvRun.Items.Clear();
                GetAllRegRun();
            }
        }

        private void cmdKillService_Click(object sender, EventArgs e)
        {
            if (cmdKillService.Text == "强制结束")
            {
                if (lsvService.SelectedItems.Count == 0)
                {
                    MessageBox.Show("你还没有选择需要Kill的服务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].SubItems[1].Text != "0")
                {
                    Process myProcess = Process.GetProcessById(Convert.ToInt32(lsvService.SelectedItems[lsvService.SelectedIndices.Count - 1].SubItems[1].Text));
                    myProcess.Kill();
                }
                lsvService.Items.Clear();
                ShowServicesList();
                MessageBox.Show("终止服务完成!!");
            }
            else if (cmdKillService.Text == "结束进程")
            {
                if (tabs.SelectedIndex == 0)
                {
                    if (lstView.Items.Count == 0)
                    {
                        MessageBox.Show("没有窗体进程可结束!!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                        return;
                    }
                    if (lstView.SelectedItems.Count == 0)
                    {
                        MessageBox.Show("你还没有选择需要结束的窗体", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    int n = 0;
                    n = lstView.SelectedIndices[0];
                    Process myProcess = Process.GetProcessById(Convert.ToInt32(lstView.SelectedItems[lstView.SelectedItems.Count-1].SubItems[1].Text));
                    try
                    {
                        myProcess.Kill();
                        lstView.Items.RemoveAt(n);
                    }
                    catch (Exception err)
                    { MessageBox.Show(err.ToString()); }
                }
                else if (tabs.SelectedIndex == 1)
                {
                    if (proLstView.Items.Count == 0)
                    {
                        MessageBox.Show("没有进程可结束!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    if (proLstView.SelectedItems.Count == 0)
                    {
                        MessageBox.Show("你还没有选择需要结束的进程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    int max = proLstView.SelectedIndices.Count;
                    for (int i = 0; i < max; i++)
                    {
                        int n = 0;
                        n = proLstView.SelectedIndices[0];
                        Process myProcess = new Process();
                        try
                        {
                             myProcess= Process.GetProcessById(Convert.ToInt32(proLstView.Items[n].SubItems[1].Text));
                        }
                        catch { proLstView.Items.RemoveAt(n);}
                        try
                        {
                            myProcess.Kill();
                            //proLstView.Items.RemoveAt(n);
                            //proLstView.Refresh();
                        }
                        catch (Exception errs)
                        { MessageBox.Show(errs.ToString()); }
                    }
                   
                }
            }
            else if (cmdKillService.Text == "按远程端口")
            {
                shutPortRemove_Click(new object(), new EventArgs());
            }
            else if (cmdKillService.Text == "禁用(&T)")
            {
                string shellRegPath = "HKEY_LOCAL_MACHINE//SOFTWARE//Microsoft//Windows NT//CurrentVersion//Winlogon".ToLower();
                string userLoadPath = "HKEY_CURRENT_USER//SOFTWARE//Microsoft//Windows NT//CurrentVersion//Windows".ToLower();
                string locaPath = "HKEY_LOCAL_MACHINE";
                string userPath = "HKEY_CURRENT_USER";
                foreach (ListViewItem item in lsvRun.Items)
                {
                    if (item.Checked == true)
                    {
                        if (item.SubItems[2].Text.Substring(0, item.SubItems[2].Text.IndexOf('//') ) == locaPath)
                        {
                            if (item.SubItems[2].Text.ToLower() == shellRegPath)
                            {
                                if (item.SubItems[0].Text.ToLower() == "shell")
                                {
                                    Registry.SetValue(shellRegPath, "shell", "Explorer.exe");
                                }
                                else if (item.SubItems[0].Text.ToLower() == "system")
                                {
                                    Registry.SetValue(shellRegPath, "System", "");
                                }
                                else if (item.SubItems[0].Text.ToLower() == "userinit")
                                {
                                    Registry.SetValue(shellRegPath, "Userinit", System.Environment.SystemDirectory + "//Userinit.exe,");
                                }
                            }
                            else
                            {
                                RegistryKey myRegistryKey = Registry.LocalMachine.CreateSubKey(item.SubItems[2].Text.Substring(item.SubItems[2].Text.IndexOf('//') + 1, item.SubItems[2].Text.Length - item.SubItems[2].Text.IndexOf('//') - 1));
                                myRegistryKey.DeleteValue(item.SubItems[0].Text, false);
                            }
                        }
                        else if (item.SubItems[2].Text.Substring(0, item.SubItems[2].Text.IndexOf('//')) == userPath)
                        {
                            if (item.SubItems[2].Text.ToLower() == userLoadPath)
                            {
                                if (item.SubItems[0].Text.ToLower() == "run")
                                {
                                    Registry.SetValue(userLoadPath, "run", "");
                                }
                                else if (item.SubItems[0].Text.ToLower() == "load")
                                {
                                    Registry.SetValue(userLoadPath, "load", "");
                                }
                            }
                            else
                            {
                                RegistryKey myRegistryKey = Registry.CurrentUser.CreateSubKey(item.SubItems[2].Text.Substring(item.SubItems[2].Text.IndexOf('//') + 1, item.SubItems[2].Text.Length - item.SubItems[2].Text.IndexOf('//') - 1));
                                myRegistryKey.DeleteValue(item.SubItems[0].Text, false);
                            }
                        }
                        //item.ForeColor = System.Drawing.Color.Blue;
                        item.Remove();
                        //RegistryKey myRegistryKey=Registry.
                        //myRegistryKey.DeleteValue(item.SubItems[2].Text + "//" + item.SubItems[0].Text);
                        //Registry.(item.SubItems[2].Text, item.SubItems[0].Text, item.SubItems[1].Text);
                    }
                };
            }
        }

        private void setTabs()
        {
            cmdStop.Text = "关闭窗体";
            cmdKillService.Text = "结束进程";
            if (isShowHideWindow == true)
            {
                cmdRunService.Visible = true;
                cmdRunService.Text = "正常窗体";
                cmdRunService.Enabled = true;
            }
            else
            {
                cmdRunService.Visible = true;
                cmdRunService.Text = "所有窗体";
                cmdRunService.Enabled = true;
            }
            cmdPause.Text = "刷新";
            cmdPause.Enabled = true;
            cmdKillService.Enabled = true;
            cmdStop.Enabled = true;
        }

        private void tabs_SelectedIndexChanged(object sender, EventArgs e)
        {
            frmMain_Resize(new object(), new EventArgs());
            Thread myThread; ;
            switch (tabs.SelectedIndex)
            {
                case 0:
                    setTabs();
                    break;
                case 1:
                    cmdPause.Text = "刷新";
                    cmdStop.Text = "模块";
                    cmdKillService.Text = "结束进程";
                    cmdRunService.Visible = true;
                    cmdRunService.Enabled = true;
                    cmdRunService.Text = "删除文件";
                    cmdPause.Enabled = true;
                    cmdKillService.Enabled = true;
                    cmdStop.Enabled = true;
                    break;
                case 2:
                    if (lsvService.Items.Count == 0 && isRunning==false)
                    {
                        myThread = new Thread(new ThreadStart(ShowServicesList));
                        myThread.Start();
                        //ShowServicesList();
                    }
                    else if (isRunning == true)
                    {
                        return;
                    }
                    else
                    {
                        lsvService.Items[0].Selected = true;
                        lsvService.Items[0].Focused = true;
                        lsvService.Focus();
                        lsvService_Click((object)lsvService.Items[0], new EventArgs());
                    }
                    cmdStop.Text = "停止(&S)";
                    cmdKillService.Text = "强制结束";
                    cmdRunService.Visible = true;
                    cmdRunService.Text = "启动(&R)";
                    cmdPause.Text = "暂停(&P)";
                    break;
                case 3:
                    cmdRunService.Visible = true;
                    cmdRunService.Enabled = true;
                    cmdStop.Enabled = true;
                    cmdPause.Enabled = true;
                    cmdKillService.Enabled = true;
                    cmdRunService.Text = "按本地IP";
                    cmdPause.Text = "按远程IP";
                    cmdStop.Text = "按本地端口";
                    cmdKillService.Text = "按远程端口";
                    if (PortLstView.Items.Count > 0 || isRunning==true) return;
                    this.PortLstView.MouseUp += new MouseEventHandler(PortLstView_MouseUp);
                    myThread = new Thread(new ThreadStart(getAllPortInfo));
                    myThread.Start();
                    break;
                case 4:
                    MessageBox.Show("功能完善中");
                    break;
                case 5:
                    cmdRunService.Visible = true;
                    cmdRunService.Enabled = true;
                    cmdRunService.Text = "添加(&I)";
                    cmdStop.Enabled = true;
                    cmdStop.Text = "启用(&S)";
                    cmdPause.Enabled = true;
                    cmdPause.Text = "刷新(&R)";
                    cmdKillService.Enabled = true;
                    cmdKillService.Text = "禁用(&T)";
                    if (lsvRun.Items.Count > 0) return;
                    GetAllRegRun();
                    break;
            }
            //MessageBox.Show(tabs.SelectedIndex.ToString() + "   " + tabs.TabPages[tabs.SelectedIndex].Text);
        }

        private void GetAllRegRun()
        {
            string localMachineRunPath = "HKEY_LOCAL_MACHINE//SOFTWARE//Microsoft//Windows//CurrentVersion//Run";
            string runSubPath = "SOFTWARE//Microsoft//Windows//CurrentVersion//Run";
            string userRunPath = "HKEY_CURRENT_USER//SOFTWARE//Microsoft//Windows//CurrentVersion//Run";
            string shellRegPath="HKEY_LOCAL_MACHINE//SOFTWARE//Microsoft//Windows NT//CurrentVersion//Winlogon";
            string userLoadPath = "HKEY_CURRENT_USER//SOFTWARE//Microsoft//Windows NT//CurrentVersion//Windows";
            string[] keys;
            keys = Registry.LocalMachine.OpenSubKey(runSubPath).GetValueNames();
            string[] userKeys;
            userKeys = Registry.CurrentUser.OpenSubKey(runSubPath).GetValueNames();
            ListViewItem lv = new ListViewItem();
            foreach (string key in keys)
            {
                lv = lsvRun.Items.Add(key);
                lv.Checked = true;
                lv.SubItems.AddRange(new string[] { Registry.GetValue(localMachineRunPath, key, "").ToString(), localMachineRunPath});
            }
            foreach (string key in userKeys)
            {
                lv = lsvRun.Items.Add(key);
                lv.Checked = true;
                lv.SubItems.AddRange(new string[] { Registry.GetValue(userRunPath , key, "").ToString(), userRunPath });
            }
            if (Registry.GetValue(shellRegPath, "shell", "explorer.exe").ToString().ToLower() == "explorer.exe" || Registry.GetValue(shellRegPath, "shell", "explorer.exe").ToString().ToLower() == System.IO.Path.GetDirectoryName(System.Environment.SystemDirectory).ToLower() + "explorer.exe")
            {
                //
            }
            else
            {
                lv = lsvRun.Items.Add("shell");
                lv.Checked = true;
                lv.SubItems.AddRange(new string[] { Registry.GetValue(shellRegPath, "shell", "").ToString(), shellRegPath });
            }
            if (Registry.GetValue(shellRegPath, "System", "").ToString() == "")
            {
                //
            }
            else
            {
                lv = lsvRun.Items.Add("System");
                lv.Checked = true;
                lv.SubItems.AddRange(new string[] { Registry.GetValue(shellRegPath, "System", "").ToString(), shellRegPath });
            }
            if (Registry.GetValue(shellRegPath, "userinit", "userinit.exe").ToString().ToLower() == "userinit.exe" || Registry.GetValue(shellRegPath, "userinit", "userinit.exe").ToString().ToLower() == "userinit.exe," || Registry.GetValue(shellRegPath, "userinit", "userinit.exe").ToString().ToLower() == System.Environment.SystemDirectory.ToLower() + "//userinit.exe," || Registry.GetValue(shellRegPath, "userinit", "userinit.exe").ToString().ToLower() == System.Environment.SystemDirectory.ToLower() + "//userinit.exe")
            {
                //
            }
            else
            {
                lv = lsvRun.Items.Add("userinit");
                lv.Checked = true;
                lv.SubItems.AddRange(new string[] { Registry.GetValue(shellRegPath, "userinit", "").ToString(), shellRegPath});
            }
            if (Registry.GetValue(shellRegPath, "run", "").ToString() == "")
            {
                //
            }
            else
            {
                lv = lsvRun.Items.Add("run");
                lv.Checked = true;
                lv.SubItems.AddRange(new string[] { Registry.GetValue(userLoadPath, "run", "").ToString(), userLoadPath });
            }
            if (Registry.GetValue(userLoadPath, "Load", "").ToString() == "")
            {
                //
            }
            else
            {
                lv = lsvRun.Items.Add("Load");
                lv.Checked = true;
                lv.SubItems.AddRange(new string[] { Registry.GetValue(userLoadPath, "Load", "").ToString(), userLoadPath });
            }
        }

        private void getAllPortInfo()
        {
            isRunning = true;
            string[,] tcpports = myportInfo.tcpPortInfo();
            PortLstView.BeginUpdate();
            for (int i = 0; i < tcpports.GetLength(0); i++)
            {
                ListViewItem item = new ListViewItem(new string[] { tcpports[i, 0], tcpports[i, 1], tcpports[i, 2], tcpports[i, 3], tcpports[i, 4], tcpports[i, 5] });
                Application.DoEvents();
                PortLstView.Items.Add(item);
            }

            string[,] udpports = myportInfo.udpPortInfo();
            for (int i = 0; i < udpports.GetLength(0); i++)
            {
                ListViewItem item = new ListViewItem(new string[] { udpports[i, 0], udpports[i, 1], udpports[i, 2], udpports[i, 3], udpports[i, 4], udpports[i, 5] });
                Application.DoEvents();
                PortLstView.Items.Add(item);
            }
            PortLstView.EndUpdate();
            isRunning = false;
        }
        private void lsvService_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            //if ((e.KeyCode == Keys.Down) || (e.KeyCode == Keys.Up))
                lsvService_Click(sender, e);
        }

        private void cmdExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void killMenuItem_Click(object sender, EventArgs e)
        {
            if (killMenuItem.Enabled==true)
            {
                if (proLstView.SelectedItems.Count == 1)
                {
                    int n = 0;
                    n = proLstView.SelectedIndices[0];
                    Process myProcess=new Process();
                    try
                    {
                        myProcess = Process.GetProcessById(Convert.ToInt32(proLstView.SelectedItems[0].SubItems[1].Text));
                    }
                    catch { proLstView.Items.RemoveAt(n);}
                    try
                    {
                        myProcess.Kill();
                        //proLstView.Items.RemoveAt(n);
                        //proLstView.Refresh();
                    }
                    catch (Exception errs)
                    { MessageBox.Show(errs.ToString()); }
                }
                else if (proLstView.SelectedItems.Count > 1)
                {
                    int max = proLstView.SelectedIndices.Count;
                    for (int i = 0; i <max; i++)
                    {
                        int n = 0;
                        n = proLstView.SelectedIndices[0];
                        Process myProcess = new Process();
                        try
                        {
                            myProcess = Process.GetProcessById(Convert.ToInt32(proLstView.Items[n].SubItems[1].Text));
                        }
                        catch { proLstView.Items.RemoveAt(n);}
                        try
                        {
                            myProcess.Kill();
                            //proLstView.Items.RemoveAt(n);
                            //proLstView.Refresh();
                        }
                        catch (Exception errs)
                        { MessageBox.Show(errs.ToString()); }
                    }
                }
            }

        }

        private void ClearMenu()
        {
            foreach (ToolStripItem myToolStripItem in runFlagMenuItem5.DropDownItems)
            {
                ToolStripMenuItem myToolStripMenuItem = new ToolStripMenuItem();
                myToolStripMenuItem = (ToolStripMenuItem)myToolStripItem;
                myToolStripMenuItem.Checked = false;
            }
        }
        private void lsvService_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (lsvService.SelectedItems.Count!=0)
                {
                    if (lsvService.Items.Count == 0) return;
                    ClearMenu();
                    if (lsvService.SelectedItems[0].SubItems[4].Text == "自动")
                    {
                        this.autoMenu.Checked = true;
                    }
                    else if (lsvService.SelectedItems[0].SubItems[4].Text == "手动")
                    {
                        this.sdMenu.Checked = true;
                    }
                    else
                    {
                        jyMenu.Checked = true;
                    }

                    if (lsvService.SelectedItems[0].SubItems[3].Text == "已启动")
                    {
                        this.runService.Enabled = false;
                        stopService.Enabled = true;
                        if (servicemanager.GetServicePauseFlag(lsvService.SelectedItems[0].SubItems[0].Text))
                        {
                            pauseService.Enabled = true;
                            this.restoreService.Enabled = false;
                        }
                        else
                        {
                            pauseService.Enabled = false;
                            this.restoreService.Enabled = false;
                        }
                    }
                    else if (lsvService.SelectedItems[0].SubItems[3].Text == "已停止")
                    {
                        this.stopService.Enabled = false;
                        this.runService.Enabled = true;
                        pauseService.Enabled = false;
                        restoreService.Enabled = false;
                    }
                    else
                    {
                        this.stopService.Enabled = true;
                        if (servicemanager.GetServicePauseFlag(lsvService.SelectedItems[0].SubItems[0].Text))
                        {
                            this.restoreService.Enabled = true;
                            pauseService.Enabled = false;
                        }
                        else
                        {
                            this.restoreService.Enabled = false;
                            pauseService.Enabled = false;
                        }

                    }

                    if (lsvService.SelectedItems[0].SubItems[1].Text != "0")
                    {
                        killService.Enabled = true;
                    }
                    else killService.Enabled = false;
                }
            }

        }

        private void PortLstView_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (PortLstView.Items.Count > 1 && PortLstView.SelectedItems[0].SubItems[0].Text != "UDP")
                {
                    shutPortRemove.Enabled = true;
                    shutPortLoca.Enabled = true;
                    shutRemovePort.Enabled = true;
                    shutLocaPort.Enabled = true;
                }
                else
                {
                    shutPortRemove.Enabled = false;
                    shutPortLoca.Enabled = false;
                    shutRemovePort.Enabled = false;
                    shutLocaPort.Enabled = false;
                }
            }
        }

        private void lstView_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (lstView.SelectedItems.Count > 0)
                {
                    if (isShowHideWindow == true)
                    {
                        //showMenu.Checked = true;
                    }
                    //else showMenu.Checked = false;
                    int hWindow = 0;
                    hWindow = Convert.ToInt32(lstView.SelectedItems[0].SubItems[2].Text);
                    if (IsWindowVisible(hWindow) == false)
                    {
                        showMenu.Text = "显示窗体(&S)";
                    }
                    else showMenu.Text = "隐藏窗体(&H)";
                }
                //else showMenu.Checked = false;
            }
        }

        private void proLstView_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (proLstView.Items.Count > 0)
                {
                    if (proLstView.SelectedItems.Count == 1)
                    {
                        if (proLstView.SelectedItems[0].SubItems[5].Text != "")
                        {
                            processMenu.Items["killMenuItem"].Enabled = true;
                            processMenu.Items["delFileripMenuItem"].Enabled = true;
                            processMenu.Items["setMenuItem"].Enabled = true;
                            try
                            {
                                Process myProcess = Process.GetProcessById(Convert.ToInt32(proLstView.SelectedItems[0].SubItems[1].Text));
                                foreach (ToolStripItem myToolStripItem in setMenuItem.DropDownItems)
                                {
                                    ToolStripMenuItem myToolStripMenuItem = new ToolStripMenuItem();
                                    myToolStripMenuItem = (ToolStripMenuItem)myToolStripItem;
                                    myToolStripMenuItem.Checked = false;
                                }
                                switch (myProcess.PriorityClass)
                                {
                                    case ProcessPriorityClass.Normal:
                                        mualMenuItem.Checked = true;
                                        break;
                                    case ProcessPriorityClass.AboveNormal:
                                        hmMenuItem.Checked = true;
                                        break;
                                    case ProcessPriorityClass.BelowNormal:
                                        dsMenuItem.Checked = true;
                                        break;
                                    case ProcessPriorityClass.RealTime:
                                        hMenuItem.Checked = true;
                                        break;
                                    case ProcessPriorityClass.Idle:
                                        sMenuItem.Checked = true;
                                        break;
                                    case ProcessPriorityClass.High:
                                        hightMenuItem.Checked = true;
                                        break;
                                }
                            }
                            catch
                            {
                                proLstView.Items.Remove(proLstView.SelectedItems[0]);
                                return;
                            }
                        }
                        else
                        {
                            processMenu.Items["killMenuItem"].Enabled = false;
                            processMenu.Items["delFileripMenuItem"].Enabled = false;
                            processMenu.Items["setMenuItem"].Enabled = false;
                        }

                    }
                    else
                    {
                        processMenu.Items["killMenuItem"].Enabled = true;
                        processMenu.Items["delFileripMenuItem"].Enabled = true;
                        processMenu.Items["setMenuItem"].Enabled = true;
                        hMenuItem.Checked = false;
                        sMenuItem.Checked = false;
                        dsMenuItem.Checked = false;
                        hmMenuItem.Checked = false;
                        mualMenuItem.Checked = false;
                        hightMenuItem.Checked = false;
                    }

                }
                else
                {
                    processMenu.Items["killMenuItem"].Enabled = false;
                    processMenu.Items["delFileripMenuItem"].Enabled = false;
                    processMenu.Items["setMenuItem"].Enabled = false;
                }

            }

        }

        private void delFileripMenuItem_Click(object sender, EventArgs e)
        {
            if (killMenuItem.Enabled == true)
            {
                delProcessFiles();
            }
        }

        private void delProcessFiles()
        {
            if (proLstView.SelectedItems.Count == 1)
            {
                bool isDelTrue = true;
                int n = 0;
                n = proLstView.SelectedIndices[0];
                int pid = Convert.ToInt32(proLstView.SelectedItems[0].SubItems[1].Text);
                Process myProcess = new Process();
                try
                {
                    myProcess = Process.GetProcessById(pid);
                }
                catch { proLstView.Items.RemoveAt(n);}
                string filePath = myProcess.MainModule.FileName;
                //ProcessModuleCollection myProcessModuleCollection = myProcess.Modules;
                //processModule unloadModule = new processModule();
                //foreach (ProcessModule myProcessModule in myProcessModuleCollection)
                //{
                //    //Application.DoEvents();
                //    unloadModule.UnLoadDll(pid, myProcessModule.FileName, myProcessModule.BaseAddress.ToInt32());
                //}
                try
                {
                    myProcess.Kill();
                }
                catch { MessageBox.Show("删除文件:" + System.IO.Path.GetFileName(filePath) + "失败!!","提示",MessageBoxButtons.OK,MessageBoxIcon.Error);}
                if (isDelTrue==true) delProcessFIle(filePath);
                try
                {
                    Process test = Process.GetProcessById(pid);
                    MessageBox.Show("删除文件:" + System.IO.Path.GetFileName(filePath) + "失败!!");
                }
                catch
                {
                    MessageBox.Show("删除文件:" + System.IO.Path.GetFileName(filePath) + "成功!!");
                    //if (proLstView.Items.Contains(proLstView.SelectedItems[0])) proLstView.Items.RemoveAt(n);
                    //proLstView.Refresh();
                }
            }
            else
            {
                int pid = 0;
                bool isDelTrue = true;
                foreach (ListViewItem item in proLstView.SelectedItems)
                {
                    pid = Convert.ToInt32(item.SubItems[1].Text);
                    string filePath = null;
                    Process myProcess = new Process();
                    try
                    {
                        myProcess = Process.GetProcessById(pid);
                        filePath = myProcess.MainModule.FileName;
                    }
                    catch
                    {
                        proLstView.Items.RemoveAt(item.Index);
                    }
                    try
                    {
                        myProcess.Kill();
                    }
                    catch { isDelTrue = false; }
                    if (isDelTrue==true) delProcessFIle(filePath);
                    try
                    {
                        Process test = Process.GetProcessById(pid);
                        //
                    }
                    catch
                    {
                        //MessageBox.Show("删除文件:" + System.IO.Path.GetFileName(filePath) + "成功!!");
                        if (proLstView.Items.Contains(item)) proLstView.Items.RemoveAt(item.Index);

                        //proLstView.Items.RemoveAt(item.Index);
                        //proLstView.Refresh();
                    }
                }
                if (isDelTrue == false) MessageBox.Show("删除文件失败!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void delProcessFIle(string ProcessPath)
        {
            System.IO.StreamWriter wt = new System.IO.StreamWriter("_del.bat", true, Encoding.Default);
            wt.WriteLine(":start");
            wt.WriteLine("del /q /"" + ProcessPath + "/"");
            wt.WriteLine("if not exist " + "/"" + ProcessPath + "/" goto ends");
            wt.WriteLine("if exist " + "/"" + ProcessPath + "/" goto start");
            wt.WriteLine("");
            wt.WriteLine(":ends");
            wt.WriteLine("del /q _del.bat");
            wt.Close();
            ShellExecute(0, "open", "_del.bat", null, Application.StartupPath, 0);
        }
        private string ConvertPriorityToString(int iPriority)
        {
            string outString = null;
            if (iPriority >= 8 && iPriority <= 9 || iPriority==11)
            {
                outString = "标准";
            }
            else if (iPriority >= 10 && iPriority <= 12 && iPriority!=11)
            {
                outString = "高于标准";
            }
            else if (iPriority >= 13 && iPriority <= 23)
            {
                outString = "高";
            }
            else if (iPriority >= 5 && iPriority <= 7)
            {
                outString = "低于标准";
            }
            else if (iPriority > 0 && iPriority <= 4)
            {
                outString = "低";
            }
            else if (iPriority >=24)
            {
                outString = "实时";
            }
            else outString = "";
            return outString;
        }
        //将进程优先级别转换成中文表示
        private string ConvertPriorityToString(ProcessPriorityClass PriorityClassName)
        {
            string outString = null;
            switch (PriorityClassName)
            {
                case ProcessPriorityClass.Normal:
                    outString= "标准";
                    break;
                case ProcessPriorityClass.AboveNormal:
                    outString= "高于标准";
                    break;
                case ProcessPriorityClass.BelowNormal:
                    outString= "低于标准";
                    break;
                case ProcessPriorityClass.RealTime:
                    outString= "实时";
                    break;
                case ProcessPriorityClass.Idle:
                    outString= "低";
                    break;
                case ProcessPriorityClass.High:
                    outString= "高";
                    break;
            }
            return outString;
        }

        private void hightMenuItem_Click(object sender, EventArgs e)
        {
            if (proLstView.SelectedItems.Count == 1)
            {
                int n = 0;
                n = proLstView.SelectedIndices[0];
                int pid = Convert.ToInt32(proLstView.SelectedItems[0].SubItems[1].Text);
                try
                {
                    Process myProcess = Process.GetProcessById(pid);
                    myProcess.PriorityClass = ProcessPriorityClass.High;
                    hightMenuItem.Checked = true;
                    proLstView.SelectedItems[0].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.High);
                }
                catch { }
            }
            else
            {
                int max = proLstView.SelectedIndices.Count;
                for (int i = 0; i < max; i++)
                {
                    int n = 0;
                    n = proLstView.SelectedIndices[i];
                    try
                    {
                        Process myProcess = Process.GetProcessById(Convert.ToInt32(proLstView.Items[n].SubItems[1].Text));
                        myProcess.PriorityClass = ProcessPriorityClass.High;
                        hightMenuItem.Checked = true;
                        proLstView.Items[n].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.High);
                    }
                    catch (Exception errs)
                    { MessageBox.Show(errs.ToString()); }
                }
            }
        }

        private void ReMenuItem_Click(object sender, EventArgs e)
        {
            proLstView.Items.Clear();
            GetProcessList();
        }

        private void hMenuItem_Click(object sender, EventArgs e)
        {
            if (proLstView.SelectedItems.Count == 1)
            {
                int n = 0;
                n = proLstView.SelectedIndices[0];
                int pid = Convert.ToInt32(proLstView.SelectedItems[0].SubItems[1].Text);
                try
                {
                    Process myProcess = Process.GetProcessById(pid);
                    myProcess.PriorityClass = ProcessPriorityClass.RealTime;
                    hMenuItem.Checked = true;
                    proLstView.SelectedItems[0].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.RealTime);
                }
                catch { }
            }
            else
            {
                int max = proLstView.SelectedIndices.Count;
                for (int i = 0; i < max; i++)
                {
                    int n = 0;
                    n = proLstView.SelectedIndices[i];
                    try
                    {
                        Process myProcess = Process.GetProcessById(Convert.ToInt32(proLstView.Items[n].SubItems[1].Text));
                        myProcess.PriorityClass = ProcessPriorityClass.RealTime;
                        hMenuItem.Checked = true;
                        proLstView.Items[n].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.RealTime);
                    }
                    catch (Exception errs)
                    { MessageBox.Show(errs.ToString()); }
                }
            }
        }

        private void hmMenuItem_Click(object sender, EventArgs e)
        {
            if (proLstView.SelectedItems.Count == 1)
            {
                int n = 0;
                n = proLstView.SelectedIndices[0];
                int pid = Convert.ToInt32(proLstView.SelectedItems[0].SubItems[1].Text);
                try
                {
                    Process myProcess = Process.GetProcessById(pid);
                    myProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
                    hmMenuItem.Checked = true;
                    proLstView.SelectedItems[0].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.AboveNormal);
                }
                catch { }
            }
            else
            {
                int max = proLstView.SelectedIndices.Count;
                for (int i = 0; i < max; i++)
                {
                    int n = 0;
                    n = proLstView.SelectedIndices[i];
                    try
                    {
                        Process myProcess = Process.GetProcessById(Convert.ToInt32(proLstView.Items[n].SubItems[1].Text));
                        myProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
                        hmMenuItem.Checked = true;
                        proLstView.Items[n].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.AboveNormal);
                    }
                    catch (Exception errs)
                    { MessageBox.Show(errs.ToString()); }
                }
            }
        }

        private void mualMenuItem_Click(object sender, EventArgs e)
        {
            if (proLstView.SelectedItems.Count == 1)
            {
                int n = 0;
                n = proLstView.SelectedIndices[0];
                int pid = Convert.ToInt32(proLstView.SelectedItems[0].SubItems[1].Text);
                try
                {
                    Process myProcess = Process.GetProcessById(pid);
                    myProcess.PriorityClass = ProcessPriorityClass.Normal;
                    mualMenuItem.Checked = true;
                    proLstView.SelectedItems[0].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.Normal);
                }
                catch { }
            }
            else
            {
                int max = proLstView.SelectedIndices.Count;
                for (int i = 0; i < max; i++)
                {
                    int n = 0;
                    n = proLstView.SelectedIndices[i];
                    try
                    {
                        Process myProcess = Process.GetProcessById(Convert.ToInt32(proLstView.Items[n].SubItems[1].Text));
                        myProcess.PriorityClass = ProcessPriorityClass.Normal;
                        mualMenuItem.Checked = true;
                        proLstView.Items[n].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.Normal);
                    }
                    catch (Exception errs)
                    { MessageBox.Show(errs.ToString()); }
                }
            }
        }

        private void dsMenuItem_Click(object sender, EventArgs e)
        {
            if (proLstView.SelectedItems.Count == 1)
            {
                int n = 0;
                n = proLstView.SelectedIndices[0];
                int pid = Convert.ToInt32(proLstView.SelectedItems[0].SubItems[1].Text);
                try
                {
                    Process myProcess = Process.GetProcessById(pid);
                    myProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
                    dsMenuItem.Checked = true;
                    proLstView.SelectedItems[0].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.BelowNormal);
                }
                catch { }
            }
            else
            {
                int max = proLstView.SelectedIndices.Count;
                for (int i = 0; i < max; i++)
                {
                    int n = 0;
                    n = proLstView.SelectedIndices[i];
                    try
                    {
                        Process myProcess = Process.GetProcessById(Convert.ToInt32(proLstView.Items[n].SubItems[1].Text));
                        myProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
                        dsMenuItem.Checked = true;
                        proLstView.Items[n].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.BelowNormal);
                    }
                    catch (Exception errs)
                    { MessageBox.Show(errs.ToString()); }
                }
            }
        }

        private void sMenuItem_Click(object sender, EventArgs e)
        {
            if (proLstView.SelectedItems.Count == 1)
            {
                int n = 0;
                n = proLstView.SelectedIndices[0];
                int pid = Convert.ToInt32(proLstView.SelectedItems[0].SubItems[1].Text);
                try
                {
                    Process myProcess = Process.GetProcessById(pid);
                    myProcess.PriorityClass = ProcessPriorityClass.Idle;
                    sMenuItem.Checked = true;
                    proLstView.SelectedItems[0].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.Idle);
                }
                catch { }
            }
            else
            {
                int max = proLstView.SelectedIndices.Count;
                for (int i = 0; i < max; i++)
                {
                    int n = 0;
                    n = proLstView.SelectedIndices[i];
                    try
                    {
                        Process myProcess = Process.GetProcessById(Convert.ToInt32(proLstView.Items[n].SubItems[1].Text));
                        myProcess.PriorityClass = ProcessPriorityClass.Idle;
                        sMenuItem.Checked = true;
                        proLstView.Items[n].SubItems[6].Text = ConvertPriorityToString(ProcessPriorityClass.Idle);
                    }
                    catch (Exception errs)
                    { MessageBox.Show(errs.ToString()); }
                }
            }
        }

        private void moduleMenuItem_Click(object sender, EventArgs e)
        {
            if (proLstView.SelectedItems.Count == 0)
            {
                MessageBox.Show("你还没有选定需要察看的进程!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int n = 0;
            n = proLstView.SelectedIndices.Count - 1;
            proLstView_DoubleClick(new object(), new EventArgs());
            proLstView.Items[n].Focused = true;
            proLstView.Focus();
        }

        private void shutMenu_Click(object sender, EventArgs e)
        {
            shutWindow();
        }

        private void showMenu_Click(object sender, EventArgs e)
        {
            if (this.lstView.SelectedItems.Count == 0)
            {
                MessageBox.Show("你还没有选定需要显示的窗体!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int hWindow=0;
            hWindow =Convert.ToInt32(lstView.SelectedItems[0].SubItems[2].Text);
            if (showMenu.Text == "显示窗体(&S)")
            {
                if (hWindow > 0)
                {
                    ShowWindow(hWindow, 5);
                    showMenu.Text = "隐藏窗体(&H)";
                    lstView.SelectedItems[0].ForeColor = System.Drawing.Color.Black;
                }
            }
            else
            {
                if (hWindow > 0)
                {
                    ShowWindow(hWindow, 0);
                    showMenu.Text = "显示窗体(&S)";
                    lstView.SelectedItems[0].ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        private void allMenu_Click(object sender, EventArgs e)
        {
            if (isShowHideWindow == true)
            {
                isShowHideWindow = false;
                //showMenu.Checked = false;
                allMenu.Text = "显示所有窗体(&A)";
            }
            else
            {
                isShowHideWindow = true;
                //showMenu.Checked = true;
                allMenu.Text = "只显示正常窗体(&A)";
            }
            setTabs();
            wTimer_Tick(new object(), new EventArgs());
        }

        private void reMenu_Click(object sender, EventArgs e)
        {
            wTimer_Tick(new object(),new EventArgs());
        }

        private void shutPortLoca_Click(object sender, EventArgs e)
        {
            if (PortLstView.Items.Count > 0 && PortLstView.SelectedItems.Count > 0)
            {
                if (PortLstView.SelectedItems[0].SubItems[1].Text.Split(':').GetLength(0) == 1) return;
                string port = PortLstView.SelectedItems[0].SubItems[1].Text.Split(':')[1].ToString();
                myportInfo.CloseLocalPort(port);
                PortLstView.Items.Clear();
                getAllPortInfo();
            }
            else MessageBox.Show("你还没有选择一个对象呢!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void shutLocaPort_Click(object sender, EventArgs e)
        {
            if (PortLstView.Items.Count > 0 && PortLstView.SelectedItems.Count>0)
            {
                string ip = PortLstView.SelectedItems[0].SubItems[1].Text.Split(':')[0].ToString();
                myportInfo.CloseLocalIP(ip);
                PortLstView.Items.Clear();
                getAllPortInfo();
            }
            else MessageBox.Show("你还没有选择一个对象呢!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //if (PortLstView.SelectedItems.Count == 1)
            //{
            //    if (PortLstView.SelectedItems[0].SubItems[0].Text == "UDP")
            //    {
            //        MessageBox.Show("不能结束UDP端口!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        return;
            //    }
            //    else
            //    {
            //        string ip = PortLstView.SelectedItems[0].SubItems[1].Text.Split(':')[0].ToString();
            //        string port = "";
            //        if (PortLstView.SelectedItems[0].SubItems[1].Text.Split(':').GetLength(0) > 1)
            //        {
            //            port = PortLstView.SelectedItems[0].SubItems[1].Text.Split(':')[1].ToString();
            //        }
            //        if (myportInfo.CloseLocalIP(ip, port) == true)
            //        {
            //            PortLstView.Items.Remove(PortLstView.SelectedItems[0]);
            //            MessageBox.Show("关闭指定端口成功!!","成功",MessageBoxButtons.OK,MessageBoxIcon.Information);
            //            return;
            //{
            //    int max=PortLstView.SelectedIndices.Count;
            //    int n = 0;
            //    int j = 1;
            //    int isAllTrue = 0;
            //    for (int i = 0; i < max; i++)
            //    {
            //        //n = PortLstView.SelectedItems.Count - j;
            //        n = PortLstView.SelectedIndices[PortLstView.SelectedIndices.Count-j];
            //        //if (PortLstView.SelectedItems[n].SubItems[0].Text != "UDP")
            //        if (PortLstView.Items[n].SubItems[0].Text != "UDP")
            //        {
            //            //if (myportInfo.CloseLocalIP(PortLstView.SelectedItems[n].SubItems[1].Text.Split(':')[0].ToString(), PortLstView.SelectedItems[n].SubItems[1].Text.Split(':')[1].ToString()) == true)
            //            if (myportInfo.CloseLocalIP(PortLstView.Items[n].SubItems[1].Text.Split(':')[0].ToString(), PortLstView.Items[n].SubItems[1].Text.Split(':')[1].ToString()) == true)
            //            {
            //                //PortLstView.Items.Remove(PortLstView.SelectedItems[n]);
            //                PortLstView.Items.RemoveAt(n);
            //            }
            //            else
            //            {
            //                j += 1;
            //                isAllTrue += 1;
            //            }
            //        }
            //    }
            //    if (isAllTrue>0)
            //    {
            //        MessageBox.Show("在关闭端口中有些可能不成功!!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            //        return;
            //    }
            //}
        }

        private void shutRemovePort_Click(object sender, EventArgs e)
        {
            if (PortLstView.Items.Count > 0 && PortLstView.SelectedItems.Count > 0)
            {
                string IP = PortLstView.SelectedItems[0].SubItems[2].Text.Split(':')[0].ToString();
                myportInfo.CloseRemoteIP(IP);
                PortLstView.Items.Clear();
                getAllPortInfo();
            }
            else MessageBox.Show("你还没有选择一个对象呢!!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        private void shutPortRemove_Click(object sender, EventArgs e)
        {
            if (PortLstView.Items.Count > 0 && PortLstView.SelectedItems.Count > 0)
            {
                if (PortLstView.SelectedItems[0].SubItems[2].Text.Split(':').GetLength(0) == 1) return;
                string port = PortLstView.SelectedItems[0].SubItems[2].Text.Split(':')[1].ToString();
                myportInfo.CloseRemotePort(port);
                PortLstView.Items.Clear();
                getAllPortInfo();
            }
            else MessageBox.Show("你还没有选择一个对象呢!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void reAllMenu_Click(object sender, EventArgs e)
        {
            PortLstView.Items.Clear();
            getAllPortInfo();
        }

        private void runService_Click(object sender, EventArgs e)
        {
            cmdRunService_Click(new object(),new EventArgs());
        }

        private void allServices_Click(object sender, EventArgs e)
        {
            ShowServicesList();
        }

        private void pauseService_Click(object sender, EventArgs e)
        {
            cmdPause_Click(new object(), new EventArgs());
        }

        private void stopService_Click(object sender, EventArgs e)
        {
            cmdStop_Click(new object(), new EventArgs());
        }

        private void restoreService_Click(object sender, EventArgs e)
        {
            cmdPause_Click(new object(), new EventArgs());
            restoreService.Enabled = false;
        }

        private void killService_Click(object sender, EventArgs e)
        {
            cmdKillService_Click(new object(), new EventArgs());
        }

        private void autoMenu_Click(object sender, EventArgs e)
        {
            servicemanager.setServiceValue(lsvService.SelectedItems[0].SubItems[0].Text, "auto");
            if (servicemanager.getservicevalue(lsvService.SelectedItems[0].SubItems[0].Text, "startmode").ToString().ToLower() == "auto")
            {
                lsvService.SelectedItems[0].SubItems[4].Text = "自动";
            }
            autoMenu.Checked = true;
        }

        private void sdMenu_Click(object sender, EventArgs e)
        {
            servicemanager.setServiceValue(lsvService.SelectedItems[0].SubItems[0].Text, "manual");
            if (servicemanager.getservicevalue(lsvService.SelectedItems[0].SubItems[0].Text, "startmode").ToString().ToLower() == "manual")
            {
                lsvService.SelectedItems[0].SubItems[4].Text = "手动";
            }
            sdMenu.Checked = true;
        }

        private void jyMenu_Click(object sender, EventArgs e)
        {
            servicemanager.setServiceValue(lsvService.SelectedItems[0].SubItems[0].Text, "disabled");
            if (servicemanager.getservicevalue(lsvService.SelectedItems[0].SubItems[0].Text, "startmode").ToString().ToLower() == "disabled")
            {
                lsvService.SelectedItems[0].SubItems[4].Text = "已禁用";
            }
            jyMenu.Checked = true;
           
        }

        private void addRunMenu_Click(object sender, EventArgs e)
        {
            cmdRunService_Click(new object(), new EventArgs());
        }

        private void choiceRunMenu_Click(object sender, EventArgs e)
        {
            cmdStop_Click(new object(), new EventArgs());
        }

        private void choicejyRunMenu_Click(object sender, EventArgs e)
        {
            cmdKillService_Click(new object(), new EventArgs());
        }

        private void sxRunMenu_Click(object sender, EventArgs e)
        {
            cmdPause_Click(new object(), new EventArgs());
        }

        private void showMainMenu_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void exitAppMenu_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void exitTrayMenu_Click(object sender, EventArgs e)
        {
            tray.Visible = false;
        }

        private void aboutAppMenu_Click(object sender, EventArgs e)
        {
            frmAbout myaboutBox = new frmAbout();
            myaboutBox.Show(this);
        }

        private void appHotKeyMenu_Click(object sender, EventArgs e)
        {
            hotKey myhotKey = new hotKey(this.Handle);
            myhotKey.Show();
        }

        private void choiceAllMenu_Click(object sender, EventArgs e)
        {
            foreach(ListViewItem lv in lsvRun.Items)
            {
                lv.Checked = true;
            }
        }

        private void choiceNoneMenu_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lv in lsvRun.Items)
            {
                lv.Checked = false;
            }
        }

        private void aboutmenu1_Click(object sender, EventArgs e)
        {
            aboutAppMenu_Click(new object(), new EventArgs());
        }

        private void aboutmenu2_Click(object sender, EventArgs e)
        {
            aboutAppMenu_Click(new object(), new EventArgs());
        }

        private void about3_Click(object sender, EventArgs e)
        {
            aboutAppMenu_Click(new object(), new EventArgs());
        }

        private void about4_Click(object sender, EventArgs e)
        {
            aboutAppMenu_Click(new object(), new EventArgs());
        }

        private void about5_Click(object sender, EventArgs e)
        {
            aboutAppMenu_Click(new object(), new EventArgs());
        }

 

        //// 验证是否能连接到远程计算机
        //public bool ConnectProcessServer(string host, string username, string password)
        //{
        //    ConnectionOptions connectionoptions = new ConnectionOptions();
        //    connectionoptions.EnablePrivileges = true;
        //    connectionoptions.Username = username;
        //    connectionoptions.Password = password;
        //    ManagementScope managementscope = new ManagementScope("////" + host + "//root//cimv2", connectionoptions);
        //    try
        //    {
        //        managementscope.Connect();
        //    }
        //    catch
        //    {
        //    }
        //    return managementscope.IsConnected;
        //}

        //private void GetProcessList()
        //{
        //    ManagementClass managementclass = new ManagementClass("////" + "." + "//root//cimv2:win32_Process");
        //    string[,] Processes = new string[managementclass.GetInstances().Count, 8];
        //    int i = 0;
        //    foreach (ManagementObject mo in managementclass.GetInstances())
        //    {
        //        //PropertyDataCollection a;
        //        //a = mo.Properties;
        //        //foreach (PropertyData b in a)
        //        //{
        //        //    MessageBox.Show(b.Name.ToString());
        //        //}
        //        Application.DoEvents();
        //        ListViewItem lv=new ListViewItem();
        //        lv=proLstView.Items.Add(mo["name"].ToString());
        //        Processes[i, 0] = mo["name"].ToString();
        //        Processes[i, 1] = mo["ProcessId"].ToString();
        //        Processes[i, 2] = GetProcessOwner(mo["ProcessId"].ToString());
        //        Processes[i, 3] = "";
        //        Processes[i, 4] = mo["WorkingSetSize"].ToString();
        //        Processes[i, 6] = ConvertPriorityToString(Convert.ToInt32(mo["Priority"]));
        //        Processes[i, 7] = Process.GetProcessById(Convert.ToInt32(mo["ProcessId"])).MainWindowTitle;
        //        try
        //        {
        //            Processes[i, 5] = mo["CommandLine"].ToString().Replace("/"", "");
        //            if (mo["CommandLine"].ToString().ToLower().IndexOf("://") == -1) Processes[i, 5] = System.IO.Path.GetDirectoryName(mo["ExecutablePath"].ToString()) + "//" + Processes[i, 5];
        //            if (mo["name"].ToString().ToLower() == "smss.exe") Processes[i, 5] = mo["ExecutablePath"].ToString();
        //            int IconIndex = 0;
        //            hIcons = ExtractAssociatedIcon(this.Handle, mo["ExecutablePath"].ToString(), ref IconIndex);
        //            Icon icons = Icon.FromHandle(hIcons);
        //            processImgLst.Images.Add(icons);
        //            lv.ImageIndex = processImgLst.Images.Count - 1;
        //            lv.SubItems.AddRange(new string[] { Processes[i, 1], Processes[i, 2], "", Processes[i, 4], Processes[i, 5], Processes[i, 6], Processes[i, 7] });
        //        }
        //        //MessageBox.Show("!11");
        //        catch
        //        {
        //            Processes[i, 5] = ""; lv.SubItems.AddRange(new string[] { Processes[i, 1], Processes[i, 2], "", Processes[i, 4], "", Processes[i, 6], Processes[i, 7] });
        //        }

        //        i++;
        //    }
        //    this.proLstView.Refresh();
        //}
    }


    public class win32servicemanager
    {
        private string strpath;
        private ManagementClass managementclass;
        public win32servicemanager(string host, string username, string password)
        {
            this.strpath = "////" + host + "//root//cimv2:win32_service";
            this.managementclass = new ManagementClass(strpath);
            if (username != null && username.Length > 0)
            {
                ConnectionOptions connectionoptions = new ConnectionOptions();
                connectionoptions.Username = username;
                connectionoptions.Password = password;
                ManagementScope managementscope = new ManagementScope("////" + host + "//root//cimv2", connectionoptions);
                this.managementclass.Scope = managementscope;
            }
        }
        // 验证是否能连接到远程计算机
        public bool remoteconnectvalidate(string host, string username, string password)
        {
            ConnectionOptions connectionoptions = new ConnectionOptions();
            connectionoptions.Username = username;
            connectionoptions.Password = password;
            ManagementScope managementscope = new ManagementScope("////" + host + "//root//cimv2", connectionoptions);
            try
            {
                managementscope.Connect();
            }
            catch
            {
            }
            return managementscope.IsConnected;
        }
        // 获取指定服务属性的值
        public object getservicevalue(string servicename, string propertyname)
        {
            ManagementObject mo = this.managementclass.CreateInstance();
            mo.Path = new ManagementPath(this.strpath + ".name=/"" + servicename + "/"");
            return mo[propertyname];
        }
        //设置指定服务的启动类型
        public void setServiceValue(string serviceName,string newPropertyName)
        {
            ManagementObject mo = this.managementclass.CreateInstance();
            mo.Path = new ManagementPath(this.strpath + ".name=/"" + serviceName + "/"");
            //mo.SetPropertyValue("StartMode", "Auto");
            //mo["StartMode"] = "Auto";
            object[] ss;
            if (newPropertyName.ToLower() == "auto")
            {
                ss = null;
            }
            else
            {
                ss = new object[] { newPropertyName };
            }
            mo.InvokeMethod("changestartmode", ss);
           
            //foreach (PropertyData a in mo.Properties)
            //{
            //    try
            //    {
            //        MessageBox.Show(a.Name.ToString() + a.Value.ToString());
            //    }
            //    catch { }
            //}
        }

        // 获取所连接的计算机的所有服务数据
        public string[,] getservicelist()
        {
            string[,] services = new string[this.managementclass.GetInstances().Count, 7];
            int i = 0;

            foreach (ManagementObject mo in this.managementclass.GetInstances())
            {
                //PropertyDataCollection a;
                //a = mo.Properties;
                //foreach (PropertyData b in a)
                //{
                //    MessageBox.Show(b.Name.ToString());
                //}
                services[i, 0] = mo["name"].ToString();
                services[i, 1] = mo["ProcessId"].ToString();
                try
                {
                    services[i, 2] = mo["Description"].ToString();
                }
                catch { services[i, 2] = ""; }
                services[i, 3] = mo["state"].ToString();
                services[i, 4] = mo["startmode"].ToString();
                services[i, 5] = mo["PathName"].ToString();
                services[i, 6] = mo["StartName"].ToString();
                i++;
            }
            return services;
        }
        // 获取所连接的计算机的指定服务数据
        public string[,] getservicelist(string servername)
        {
            return getservicelist(new string[] { servername });
        }
        // 获取所连接的计算机的的指定服务数据
        public string[,] getservicelist(string[] servernames)
        {
            string[,] services = new string[servernames.Length, 7];
            ManagementObject mo = this.managementclass.CreateInstance();
            for (int i = 0; i < servernames.Length; i++)
            {
                mo.Path = new ManagementPath(this.strpath + ".name=/"" + servernames[i] + "/"");
                services[i, 0] = mo["name"].ToString();
                services[i, 1] = mo["ProcessId"].ToString();
                try
                {
                    services[i, 2] = mo["Description"].ToString();
                }
                catch { services[i, 2] = ""; }
                services[i, 3] = mo["state"].ToString();
                services[i, 4] = mo["startmode"].ToString();
                services[i, 5] = mo["PathName"].ToString();
                services[i, 6] = mo["StartName"].ToString();
            }
            return services;
        }
        // 开始指定的服务
        public string startservice(string servicename)
        {
            string strrst = null;
            ManagementObject mo = this.managementclass.CreateInstance();
            mo.Path = new ManagementPath(this.strpath + ".name=/"" + servicename + "/"");
            try
            {
               
                if (mo["state"].ToString().ToLower() == "stopped")//!(bool)mo["acceptstop"]
                {
                    mo.InvokeMethod("startservice", null);
                    if (getservicevalue(servicename, "state").ToString().ToLower() == "stopped") return "启动服务失败";
                          
                }
            }
            catch (ManagementException e)
            {
                strrst = e.Message;
            }
           
            return strrst;
        }
        // 暂停指定的服务
        public string pauseservice(string servicename)
        {
            string strrst = null;
            ManagementObject mo = this.managementclass.CreateInstance();
            mo.Path = new ManagementPath(this.strpath + ".name=/"" + servicename + "/"");
            try
            {
                //判断是否可以暂停
                if ((bool)mo["acceptpause"] && mo["state"].ToString().ToLower() == "running")
                {
                    mo.InvokeMethod("pauseservice", null);
                    //if (mo.GetPropertyValue("state").ToString().ToLower() != "running") return "停止服务失败";
                }
            }
            catch (ManagementException e)
            {
                strrst = e.Message;
            }
            return strrst;
        }

        //判断指定服务是不是可以暂停
        public bool GetServicePauseFlag(string serviceName)
        {
            ManagementObject mo = this.managementclass.CreateInstance();
            mo.Path = new ManagementPath(this.strpath + ".name=/"" + serviceName + "/"");
            if ((bool)mo["acceptpause"] == true)
            {
                return true;
            }
            else return false;
        }

        // 恢复指定的服务
        public string resumeservice(string servicename)
        {
            string strrst = null;
            ManagementObject mo = this.managementclass.CreateInstance();
            mo.Path = new ManagementPath(this.strpath + ".name=/"" + servicename + "/"");
            try
            {
                //判断是否可以恢复
                if ((bool)mo["acceptpause"] && mo["state"].ToString().ToLower() == "paused")
                    mo.InvokeMethod("resumeservice", null);
            }
            catch (ManagementException e)
            {
                strrst = e.Message;
            }
            return strrst;
        }
        // 停止指定的服务
        public string stopservice(string servicename)
        {
            string strrst = null;
            ManagementObject mo = this.managementclass.CreateInstance();
            mo.Path = new ManagementPath(this.strpath + ".name=/"" + servicename + "/"");
            try
            {
                //判断是否可以停止
                if ((bool)mo["acceptstop"])//(string)mo["state"]=="running"
                {
                    mo.InvokeMethod("stopservice", null);
                    if (getservicevalue(servicename, "state").ToString().ToLower() != "stopped") return "停止服务失败";
                }
                else return "此服务无法停止你可以选择" + "/"强制结束" + "/"来结束服务进程";
            }
            catch (ManagementException e)
            {
                strrst = e.Message;
            }
            return strrst;
        }
    }

    //public class AddToListview
    //{
    //    private string sProcessName;
    //    private string sProcessId;
    //    private string sProcessOwner;
    //    private string scpu;
    //    private string sWorkingSet;
    //    private string sFilePath;
    //    private string sPriority;
    //    private string sMainWindowTitle;

    //    public AddToListview(string ProcessName, string ProcessId, string ProcessOwner,string cpu, string WorkingSet, string FilePath, string Priority, string MainWindowTitle)
    //    {
    //        this.sProcessName = ProcessName;
    //        this.sProcessId = ProcessId;
    //        this.sProcessOwner = ProcessOwner;
    //        this.scpu = cpu;
    //        this.sWorkingSet = WorkingSet;
    //        this.sFilePath = FilePath;
    //        this.sPriority = Priority;
    //        this.sMainWindowTitle = MainWindowTitle;
    //    }

    //    public void AddToProcessListView()
    //    {
    //        //MessageBox.Show(sProcessName);
    //        frmMain myfrmMain = new frmMain();
    //        ListViewItem lsv = new ListViewItem();
    //        lsv = myfrmMain.proLstView.Items.Add(sProcessName);
    //        lsv.SubItems.AddRange(new string[] { sProcessId, sProcessOwner, scpu, sWorkingSet, sFilePath, sPriority, sMainWindowTitle });
    //    }
    //}

    public class ListViewItemComparer : IComparer
    {
        private int col;
        public ListViewItemComparer()
        {
            col = 0;
        }
        public ListViewItemComparer(int column)
        {
            col = column;
        }
        public int Compare(object x, object y)
        {
            return string.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
        }
    }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:326844次
    • 积分:4463
    • 等级:
    • 排名:第7122名
    • 原创:81篇
    • 转载:0篇
    • 译文:2篇
    • 评论:434条
    文章分类
    最新评论
    chenhui530新浪博客