private void Initialize() { consoleHandler = new NativeMethods.ConHndlr(this.ConsoleHandlerProc); if (!UnsafeNativeMethods.SetConsoleCtrlHandler(consoleHandler, 1)) { Debug.Fail("Failed to install console handler."); consoleHandler = null; } windowHandle = CreateBroadcastWindow(); Debug.Assert(windowHandle != IntPtr.Zero, "CreateBroadcastWindow failed"); AppDomain.CurrentDomain.ProcessExit += new EventHandler(SystemEvents.Shutdown); AppDomain.CurrentDomain.DomainUnload += new EventHandler(SystemEvents.Shutdown); }
public static extern bool SetConsoleCtrlHandler(NativeMethods.ConHndlr handler, int add);
private void Dispose() { if (windowHandle != IntPtr.Zero) { if (registeredSessionNotification) { UnsafeNativeMethods.WTSUnRegisterSessionNotification(new HandleRef(systemEvents, systemEvents.windowHandle)); } IntPtr handle = windowHandle; windowHandle = IntPtr.Zero; HandleRef href = new HandleRef(this, handle); //we check IsWindow because Application may have rudely destroyed our broadcast window. //if this were true, we want to unregister the class. if (UnsafeNativeMethods.IsWindow(href) && DefWndProc != IntPtr.Zero) { UnsafeNativeMethods.SetWindowLong(href, NativeMethods.GWL_WNDPROC, new HandleRef(this, DefWndProc)); //set our sentinel value that we will look for upon initialization to indicate //the window class belongs to an unloaded appdomain and therefore should not be used. UnsafeNativeMethods.SetClassLong(href, NativeMethods.GCL_WNDPROC, DefWndProc); } // If DestroyWindow failed, it is because we're being // shutdown from another thread. In this case, locate the // DefWindowProc call in User32, sling the window back to it, // and post a nice fat WM_CLOSE // if (UnsafeNativeMethods.IsWindow(href) && !UnsafeNativeMethods.DestroyWindow(href)) { UnsafeNativeMethods.PostMessage(href, NativeMethods.WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } else { IntPtr hInstance = UnsafeNativeMethods.GetModuleHandle(null); UnsafeNativeMethods.UnregisterClass(className, new HandleRef(this, hInstance)); } } if (consoleHandler != null) { UnsafeNativeMethods.SetConsoleCtrlHandler(consoleHandler, 0); consoleHandler = null; } }