如何检测新进程是否在计时器c#上运行

时间:2017-03-26 22:36:11

标签: c# winforms process

我如何确定新进程是否正在运行(不是特定的,只是任何新进程),并将其添加到listView及其来自计时器的图标。

目前我有这个,它所做的只是重置列表视图,无论是否存在新进程。我希望它不重置listview,而是将新的一个添加到listview中。同样,删除不再存在的进程。

public UserControl5()
        {
            InitializeComponent();
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        class Win32
        {
            public const uint SHGFI_ICON = 0x100;
            public const uint SHGFI_LARGEICON = 0x0;    // 'Large icon
            public const uint SHGFI_SMALLICON = 0x1;    // 'Small icon

            [DllImport("shell32.dll")]
            public static extern IntPtr SHGetFileInfo(string pszPath,
                                        uint dwFileAttributes,
                                        ref SHFILEINFO psfi,
                                        uint cbSizeFileInfo,
                                        uint uFlags);
        }

        private int nIndex = 0;
        private void UserControl5_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;


        }
private void timer1_Tick(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            listView1.View = View.Details;
            listView1.Columns.Clear();
            listView1.Columns.Add("Processes");
            listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

            IntPtr hImgSmall;    //the handle to the system image list
            IntPtr hImgLarge;    //the handle to the system image list
            string fName;        // 'the file name to get icon from
            SHFILEINFO shinfo = new SHFILEINFO();

            listView1.SmallImageList = imageList1;
            listView1.LargeImageList = imageList1;


            Process[] processlist = Process.GetProcesses();

            foreach (Process process in processlist)
            {
                try
                {
                    String fileName = process.MainModule.FileName;
                    String processName = process.ProcessName;
                    hImgSmall = Win32.SHGetFileInfo(fileName, 0, ref shinfo,
                                                  (uint)Marshal.SizeOf(shinfo),
                                                   Win32.SHGFI_ICON |
                                                   Win32.SHGFI_SMALLICON);

                    //Use this to get the large Icon
                    //hImgLarge = SHGetFileInfo(fName, 0,
                    //ref shinfo, (uint)Marshal.SizeOf(shinfo),
                    //Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);
                    //The icon is returned in the hIcon member of the shinfo
                    //struct
                    System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

                    imageList1.Images.Add(myIcon);

                    //Add file name and icon to listview



                    listView1.Items.Add(Path.GetFileName(System.IO.Path.GetFileNameWithoutExtension(fileName)), nIndex++);
                    //nIndex++


                }
                catch
                {

                }
            }
            }

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedIndices.Count <= 0)
            {
                return;
            }
            int intselectedindex = listView1.SelectedIndices[0];
            if (intselectedindex >= 0)
            {
                textBox1.Text = listView1.Items[intselectedindex].Text;
            }
        }

1 个答案:

答案 0 :(得分:1)

选项1 - 作为选项,您可以使用计时器并使用Process.GetProcesses()Win32_Process上的WMI查询获取流程信息。然后根据他们的ProcessId将现有流程列表与新列表进行比较。然后,您可以找到流程并删除流程。

选项2 - 作为另一种选择,您可以使用ManagementEventWatcher来监控Win32_ProcessStartTrace以检测新程序的开始,并使用Win32_ProcessStopTrace来检测停止进程。

您可以订阅监视对象的EventArrived ManagementEventWatcher事件。在这种情况下,您可以找到有关流程的ProcessIDProcessName等信息。

使用观察者和事件时,请记住:

  • EventArrived将在与线程不同的线程中引发,如果您需要操作UI,则需要使用Invoke
  • 你应该停止观察者并将其丢弃在OnFormClosed
  • 您应该添加对System.Management.dll
  • 的引用
  • 您应该添加using System.Management;
  • 您需要以管理员身份运行程序。

示例

ManagementEventWatcher startWatcher;
ManagementEventWatcher stopWatcher;
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    startWatcher = new ManagementEventWatcher("Select * From Win32_ProcessStartTrace");
    startWatcher.EventArrived += new EventArrivedEventHandler(startWatcher_EventArrived);
    stopWatcher = new ManagementEventWatcher("Select * From Win32_ProcessStopTrace");
    stopWatcher.EventArrived += new EventArrivedEventHandler(stopWatcher_EventArrived);
    startWatcher.Start();
    stopWatcher.Start();
}
void startWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    MessageBox.Show(string.Format("{0} started", (string)e.NewEvent["ProcessName"]));
}
void stopWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    MessageBox.Show(string.Format("{0} stopped", (string)e.NewEvent["ProcessName"]));
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
    startWatcher.Stop();
    stopWatcher.Stop();
    startWatcher.Dispose();
    stopWatcher.Dispose();
    base.OnFormClosed(e);
}