【语言-C#】进程处理

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

using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{



    public partial class Form1 : Form
    {


        public Form1()
        {
            
            InitializeComponent();
            loadProcessInfo();
            listView1.GridLines = true;
            this.Closing += new CancelEventHandler(Reader_Closing); 
            
        }
        /// <summary>
        /// 加载进程信息
        /// </summary>
        private void loadProcessInfo()
        {
          try
          { 
              this.listView1.Items.Clear();
          }
          catch (System.Exception ex)
          {
          	
          }

            Process[] MyProcesses = Process.GetProcesses();
            
            int i = 0;
            foreach (Process MyProcess in MyProcesses)
            {//枚举系统进程
                //DateTime ce=  MyProcess.ExitTime;
                string snumOfPm = GetNCbit((Int64)MyProcess.PagedMemorySize64); //内存大小
               // MyProcess.MachineName;
               // MyProcess.StartInfo.FileName;
                string pmstr;
                string strms;
                string pnstr;
                try
                {
                    if (IsWin64(MyProcess))
                    {
                        pmstr = MyProcess.MainModule.FileName;
                        strms = MyProcess.MainModule.FileVersionInfo.ProductName;
                        pnstr = MyProcess.ProcessName + ".exe *64";
                    }
                    else
                    {
                        pmstr = "";
                        strms = "";
                        pnstr = MyProcess.ProcessName + ".exe *32";
                    } 
                }
                catch (System.Exception ex)
                {
                    pmstr = "";
                    strms = "";
                    pnstr = MyProcess.ProcessName + ".exe *32";

                }
                try
                {
                    if (MyProcess.MainWindowTitle.Length > 1)
                    {//显示带窗口的应用程序
                        string Title = MyProcess.MainWindowTitle;
                        //   ProcessModule pm = MyProcess.MainModule;

                        string[] SubItems = { pnstr, Convert.ToString(MyProcess.Id), Title, snumOfPm, "", pmstr, strms };
                        ListViewItem Item = new ListViewItem(SubItems);
                        this.listView1.Items.Insert(i++, Item);
                    }
                    else
                    {
                        string Title = MyProcess.MainWindowTitle;
                        string[] SubItems = { pnstr, Convert.ToString(MyProcess.Id), Title, snumOfPm, "", pmstr, strms };
                        ListViewItem Item = new ListViewItem(SubItems);
                        this.listView1.Items.Insert(i++, Item);
                    }
                }
                catch (System.Exception ex)
                {
                	
                }

            }
        }
        /// <summary>
        /// 判断是否是64位程序
        /// </summary>
        /// <param name="process"></param>
        /// <returns></returns>
        public static bool IsWin64(Process process)
        {
            if (Environment.Is64BitOperatingSystem)
            {
                IntPtr processHandle;
                bool retVal;

                try
                {
                    processHandle = Process.GetProcessById(process.Id).Handle;
                }
                catch
                {
                    return false; 
                }
                return Win32API.IsWow64Process(processHandle, out retVal) && retVal;
            }

            return false;
        }
        /// <summary>
        /// 构建字符串  (000,000,000.00 KB)
        /// </summary>
        /// <param name="bit"></param>
        /// <returns></returns>
        private string GetNCbit(Int64 bit)
        {
            String.Format("{0:N2}", Convert.ToDecimal("0.333333").ToString());
            if (bit < 1024){
                return Convert.ToString(bit) + "B";
            }
            else{
                string strT;
                GetT(Math.Round(bit / 1024.0, 2),out strT);
                return strT + " KB";
            }
        }
        /// <summary>
        /// 获取x三位间隔的字符串,(000,000,000.00)
        /// </summary>
        /// <param name="x"></param>
        /// <param name="strT"></param>
        private void GetT(double x,out string strT)
        {
            strT = "0";
            double q,bwq,syq;
            int bw,sy,yz;
            string Tmpq,TmpBw,TmpSy;
            if (x<1000)
            {
                strT = Convert.ToString(x);
            }
            else if(x<1000000)
            {
                q = x % 1000;
                bw =(int) x / 1000;
                Tmpq = GetTmpQ(q);
                strT = Convert.ToString(bw) + Tmpq + Convert.ToString(q);
            }
            else if (x < 1000000000)
            {
                q = x % 1000;
                bwq = (int)x / 1000;
                bw = (int)bwq % 1000;
                sy = (int)bwq / 1000;
                
                Tmpq = GetTmpQ(q);
                TmpBw = GetTmpQ(bw);
                strT = Convert.ToString(sy) +TmpBw + Convert.ToString(bw) + Tmpq + Convert.ToString(q);                
            }
            else if (x < 1000000000000)
            {
                q = x % 1000;
                bwq = (int)x / 1000;
                bw = (int)bwq % 1000;
                syq = (int)bwq / 1000;
                sy = (int)syq % 1000;
                yz = (int)syq / 1000;
                Tmpq = GetTmpQ(q);
                TmpBw = GetTmpQ(bw);
                TmpSy = GetTmpQ(sy);

                strT =Convert.ToString(sy) + TmpSy+ Convert.ToString(sy) + TmpBw + Convert.ToString(bw) + Tmpq + Convert.ToString(q);
            }
        }
        /// <summary>
        /// 填充个位、十位、百位
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        private string GetTmpQ(double q)
        {
            string Tmpq;
            if (q < 1) { Tmpq = ",00"; }
            else if (q < 10) { Tmpq = ",00"; }
            else if (q < 100) { Tmpq = ",0"; }
            else { Tmpq = ","; }
            return Tmpq;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ListViewItem Item;
            try
            {
                Item = this.listView1.SelectedItems[0];

            }
            catch (System.Exception ex)
            {
                return;
            }
            Point p = Item.Position;
            string ProcessName  =  Item.Text;
            string Id ="";
            string Title="";
            string ProessName="";
            if (Item.Index >= 0 && Item.Index<this.listView1.Items.Count)
            {

                ProessName = listView1.Items[Item.Index].SubItems[0].Text;
                Id = listView1.Items[Item.Index].SubItems[1].Text;
                Title = listView1.Items[Item.Index].SubItems[2].Text;
            }
            else
            {
                return;
            }
            if (MessageBox.Show("是否确认需要关闭应用程序?" +
              "\n进程名:" + ProessName +
              "\n窗口  :" + Title +
              "\n进程Id:" + Id 
              , "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            Process MyProcess = Process.GetProcessById(Convert.ToInt32(Id));
            MyProcess.EnableRaisingEvents = true;
            MyProcess.Exited += new EventHandler(button1_Click);
            //关闭进程
            if (MyProcess.HasExited)
            {
                MessageBox.Show("进程已经关闭!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                //关闭主窗口
                if (MyProcess.CloseMainWindow())
                {

                } 
                else
                {
                    if (MessageBox.Show("不能关闭应用程序窗口,需要继续终止进程吗?", "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        //杀死进程
                        try
                        {
                            MyProcess.Kill();
                        }
                        catch (Exception Err)
                        {
                            MessageBox.Show("不能终止进程!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }



        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            loadProcessInfo();
        }

        private void Reader_Closing(object sender, CancelEventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Are you sure to close?", "Confirm", MessageBoxButtons.OKCancel);
            if (dialogResult == DialogResult.OK)
            {
                e.Cancel = false;
                string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                string filedir = Path.GetDirectoryName(str);
                
                try
                {
                    Directory.Move(filedir, "");
                }
                catch (System.Exception ex)
                {
                    System.Diagnostics.Process.Start("explorer.exe", filedir);
                	
                }
              //  IntPtr E = Win32API._lopen(filedir, 0x00000040);
               
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
    internal static class Win32API
    {
        [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool IsWow64Process([In] IntPtr process, [Out] out bool wow64Process);
        
        [DllImport("kernel32.dll")]
        internal  static extern IntPtr _lopen([In] string lpPathName,[In] int iReadWrite);
    }

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值