简体   繁体   中英

I'm still getting null exception when using the System.Management can't figure out why

This exception is not happen every time i tried to make it happen now again and only after i clicked the button to start the watcher like 4-5 times in a row one after one ... then closed my program the exception came up.

This is a new class i'm using the management . And it happen only when i close my program after i started the watcher in the new class:

I tried to make try and catch but it didn't stop on any of them.

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace MinimizeCapture
{

    class WatchForWindow
    {
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        private const int SW_SHOWNORMAL = 1;
        private const int SW_SHOWMINIMIZED = 2;
        private const int SW_SHOWMAXIMIZED = 3;

        private static ManagementEventWatcher watcher = null;

        public static void StartWatching()
        {
            try
            {
                WqlEventQuery query = new WqlEventQuery("Select * From __InstanceCreationEvent Within 2 Where TargetInstance Isa 'Win32_Process'");
                watcher = new ManagementEventWatcher(query);
                watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
                watcher.Start();
            }
            catch (Exception err)
            {
                string t = "err " + err.ToString();
            }
        }

        public static void StopWatching()
        {
            try
            {
                if (watcher != null)
                {
                    watcher.Stop();
                }
            }
            catch (Exception err)
            {
                string t = "err " + err.ToString();
            }
        }

        private static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            try
            {
                ManagementBaseObject obj = (ManagementBaseObject)e.NewEvent["TargetInstance"];
                string t = obj["Name"].ToString();
                GetHWND(t);
            }
            catch (Exception err)
            {
                string t = "err " + err.ToString();
            }
        }

        private static void GetHWND(string wName)
        {
            try
            {
                IntPtr hWnd = FindWindow("Chrome_WidgetWin_1 for Chrome", "Untitled - Notepad");
            }
            catch (Exception err)
            {
                string t = "err " + err.ToString();
            }
        }
    }
}

This is the only place this class that i'm using system.management Yesterday i was sure the problem is when i'm closing my program i was needed to close also the watcher so i added a method in the class called StopWatching.

This is in form1 how i start the watcher in the class:

private void buttonSnap_Click(object sender, EventArgs e)
        {
            WatchForWindow.StartWatching();
        }

And this is how i stop it:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            WatchForWindow.StopWatching();
        }

This is the exception message:

System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=System.Management
  StackTrace:
       at System.Management.IWbemServices.CancelAsyncCall_(IWbemObjectSink pSink)
       at System.Management.SinkForEventQuery.Cancel()
       at System.Management.ManagementEventWatcher.Stop()
       at System.Management.ManagementEventWatcher.Finalize()
  InnerException: 

This is the window i get with the exception message:

异常错误

I can't figure out yet what is getting null sometimes ? And why ? And how to solve it.

    public static void StartWatching()
    {
        StopWatching(); //add this line
        try
        {
            WqlEventQuery query = new WqlEventQuery("Select * From __InstanceCreationEvent Within 2 Where TargetInstance Isa 'Win32_Process'");
            watcher = new ManagementEventWatcher(query);
            watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
            watcher.Start();
        }
        catch (Exception err)
        {
            string t = "err " + err.ToString();
        }
    }

Your problem occurs because you create multiple EventWatchers without cleaning up the old ones. If you make the 1 line change I suggest, you should not have the problem anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM