.Net检测应用程序启动

时间:2014-07-18 10:26:55

标签: c# wmi

我目前正在尝试监控正在启动和关闭的应用程序,下面是我当前的代码,但无论何时执行我都会收到拒绝访问错误,任何深入的想法或理由为什么会发生这种情况将非常感激

    class Program
        {
            static void Main(string[] args)
            {
                ManagementScope scope = new ManagementScope("root\\CIMV2");
                scope.Options.EnablePrivileges = true;
                try
                    {
                        ManagementEventWatcher startWatch = new ManagementEventWatcher(
                            new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
                        startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived);
                        startWatch.Start();
                        ManagementEventWatcher stopWatch = new ManagementEventWatcher(
                        new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
                        stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived);
                        stopWatch.Start();
                        Console.WriteLine("Press any key to exit");
                        while (!Console.KeyAvailable) System.Threading.Thread.Sleep(50);
                        startWatch.Stop();
                        stopWatch.Stop();
                    }
                catch (ManagementException e)
                    {
                        Console.WriteLine(e);
                        Console.ReadKey();
                    }
            }
            static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) 
{
        Console.WriteLine("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value);
      }

      static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) 
{
        Console.WriteLine("Process started: {0}", e.NewEvent.Properties["ProcessName"].Value);
      }
            }

1 个答案:

答案 0 :(得分:0)

可能发生此错误是因为您没有在提升模式下运行应用程序。如果从Visual Studio运行应用程序,则以提升模式运行Visual Studio,否则以提升模式运行应用程序exe:

右键单击VS exe /快捷方式,然后选择"以管理员身份运行"选项。

如果您直接运行应用程序exe,请右键单击您的应用程序exe并选择"以管理员身份运行"