internal MediaContextNotificationWindow(MediaContext ownerMediaContext) { // Remember the pointer to the owner MediaContext that we'll forward the broadcasts to. _ownerMediaContext = ownerMediaContext; // Create a top-level, invisible window so we can get the WM_DWMCOMPOSITIONCHANGED // and other DWM notifications that are broadcasted to top-level windows only. HwndWrapper hwndNotification; hwndNotification = new HwndWrapper(0, NativeMethods.WS_POPUP, 0, 0, 0, 0, 0, "MediaContextNotificationWindow", IntPtr.Zero, null); _hwndNotificationHook = new HwndWrapperHook(MessageFilter); _hwndNotification = new SecurityCriticalDataClass<HwndWrapper>(hwndNotification); _hwndNotification.Value.AddHook(_hwndNotificationHook); _isDisposed = false; // // On Vista, we need to know when the Magnifier goes on and off // in order to switch to and from software rendering because the // Vista Magnifier cannot magnify D3D content. To receive the // window message informing us of this, we must tell the DWM // we are MIL content. // // The Win7 Magnifier can magnify D3D content so it's not an // issue there. In fact, Win7 doesn't even send the WM. // // If the DWM is not running, this call will result in NoOp. // ChangeWindowMessageFilter(s_dwmRedirectionEnvironmentChanged, 1 /* MSGFLT_ADD */); MS.Internal.HRESULT.Check(MilContent_AttachToHwnd(_hwndNotification.Value.Handle)); }
private void SetUpInputHooks() { IKeyboardInputSink sink; new UIPermission(PermissionState.Unrestricted).Assert(); //BlessedAssert try { _inputPostFilter = new HwndWrapperHook(BrowserInteropHelper.PostFilterInput); HwndSource hwndSource = base.HwndSourceWindow; hwndSource.HwndWrapper.AddHookLast(_inputPostFilter); sink = (IKeyboardInputSink)hwndSource; } finally { UIPermission.RevertAll(); } new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); //BlessedAssert try { Debug.Assert(sink.KeyboardInputSite == null); sink.KeyboardInputSite = new KeyInputSite(new SecurityCriticalData <IKeyboardInputSink>(sink)); } finally { SecurityPermission.RevertAll(); } }
//+--------------------------------------------------------------------- // // Internal Methods // //---------------------------------------------------------------------- #region Internal Methods /// <summary> /// Sets the owner MediaContext and creates the notification window. /// </summary> internal MediaContextNotificationWindow(MediaContext ownerMediaContext) { // Remember the pointer to the owner MediaContext that we'll forward the broadcasts to. _ownerMediaContext = ownerMediaContext; // Create a top-level, invisible window so we can get the WM_DWMCOMPOSITIONCHANGED // and other DWM notifications that are broadcasted to top-level windows only. HwndWrapper hwndNotification; hwndNotification = new HwndWrapper(0, NativeMethods.WS_POPUP, 0, 0, 0, 0, 0, "MediaContextNotificationWindow", IntPtr.Zero, null); _hwndNotificationHook = new HwndWrapperHook(MessageFilter); _hwndNotification = new SecurityCriticalDataClass <HwndWrapper>(hwndNotification); _hwndNotification.Value.AddHook(_hwndNotificationHook); _isDisposed = false; // // On Vista, we need to know when the Magnifier goes on and off // in order to switch to and from software rendering because the // Vista Magnifier cannot magnify D3D content. To receive the // window message informing us of this, we must tell the DWM // we are MIL content. // // The Win7 Magnifier can magnify D3D content so it's not an // issue there. In fact, Win7 doesn't even send the WM. // // If the DWM is not running, this call will result in NoOp. // ChangeWindowMessageFilter(s_dwmRedirectionEnvironmentChanged, 1 /* MSGFLT_ADD */); MS.Internal.HRESULT.Check(MilContent_AttachToHwnd(_hwndNotification.Value.Handle)); }
internal void AddHookLast(HwndWrapperHook hook) { if (_hooks == null) { _hooks = new SecurityCriticalDataClass <WeakReferenceList>(new WeakReferenceList()); } _hooks.Value.Add(hook); }
public void RemoveHook(HwndWrapperHook hook) { //VerifyAccess(); if (_hooks != null) { _hooks.Value.Remove(hook); } }
/// <summary> /// This is the WNDPROC that gets inserted into the window's /// WNDPROC chain. It responds to various conditions that /// would cause this HwndSubclass object to unsubclass the window, /// and then calls the delegate specified to the HwndSubclass /// constructor to process the message. If the delegate does not /// handle the message, the message is then passed on down the /// WNDPROC chain for further processing. /// </summary> /// <param name="hwnd"> /// The window that this message was sent or posted to. /// </param> /// <param name="msg"> /// The message that was sent or posted. /// </param> /// <param name="wParam"> /// A parameter for the message that was sent or posted. /// </param> /// <param name="lParam"> /// A parameter for the message that was sent or posted. /// </param> /// <returns> /// The value that is the result of processing the message. /// </returns> public IntPtr SubclassWndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam) { IntPtr retval = IntPtr.Zero; bool handled = false; // If we are unattached and we receive a message, then we must have // been used as the original window proc. In this case, we insert // ourselves as if the original window proc had been DefWindowProc. if (_bond == Bond.Unattached) { HookWindowProc(hwnd, new NativeStructs.WndProc(SubclassWndProc), DefWndProc); } else if (_bond == Bond.Detached) { throw new InvalidOperationException(); } if (msg == s_detachMessage) { // We received our special message to detach. Make sure it is intended // for us by matching the bridge. if (wParam == (IntPtr)_gcHandle) { retval = Detach(false) ? (IntPtr)1 : (IntPtr)0; handled = true; } } else { HwndWrapperHook hook = _hook.Target as HwndWrapperHook; if (_bond == Bond.Attached && hook != null) { retval = hook(hwnd, msg, wParam, lParam, ref handled); } // Handle WM_NCDESTROY explicitly to forcibly clean up. if (msg == NativeConstants.WM_NCDESTROY) { // The fact that we received this message means that we are // still in the call chain. This is our last chance to clean // up, and no other message should be received by this window // proc again. It is OK to force a cleanup now. Dispose(); // Always pass the WM_NCDESTROY message down the chain! handled = false; } } // If our window proc didn't handle this message, pass it on down the // chain. if (!handled) { retval = CallOldWindowProc(hwnd, msg, wParam, lParam); } return(retval); }
public void AddHook(HwndWrapperHook hook) { //VerifyAccess(); if (_hooks == null) { _hooks = new SecurityCriticalDataClass <WeakReferenceList>(new WeakReferenceList()); } _hooks.Value.Insert(0, hook); }
public void AddHook(HwndWrapperHook hook) { //VerifyAccess(); if (_hooks == null) { _hooks = new WeakReferenceList(); } _hooks.Add(hook); }
private void Initialize(bool fTrusted) { _fTrusted = new SecurityCriticalDataForSet <bool> (fTrusted); _hwndSubclassHook = new HwndWrapperHook(SubclassWndProc); _handlerLayoutUpdated = new EventHandler(OnLayoutUpdated); _handlerEnabledChanged = new DependencyPropertyChangedEventHandler(OnEnabledChanged); _handlerVisibleChanged = new DependencyPropertyChangedEventHandler(OnVisibleChanged); PresentationSource.AddSourceChangedHandler(this, new SourceChangedEventHandler(OnSourceChanged)); _weakEventDispatcherShutdown = new WeakEventDispatcherShutdown(this, this.Dispatcher); }
private void SetUpInputHooks() { IKeyboardInputSink sink; _inputPostFilter = new HwndWrapperHook(BrowserInteropHelper.PostFilterInput); HwndSource hwndSource = base.HwndSourceWindow; hwndSource.HwndWrapper.AddHookLast(_inputPostFilter); sink = (IKeyboardInputSink)hwndSource; Debug.Assert(sink.KeyboardInputSite == null); sink.KeyboardInputSite = new KeyInputSite(new SecurityCriticalData <IKeyboardInputSink>(sink)); }
/// <summary> /// This HwndSubclass constructor binds the HwndSubclass object to the /// specified delegate. This delegate will be called to process /// the messages that are sent or posted to the window. /// </summary> /// <param name="hook"> /// The delegate that will be called to process the messages that /// are sent or posted to the window. /// </param> /// <returns> /// Nothing. /// </returns> internal HwndSubclass(HwndWrapperHook hook) { if (hook == null) { throw new ArgumentNullException("hook"); } _bond = Bond.Unattached; _hook = new WeakReference(hook); // Allocate a GC handle so that we won't be collected, even if all // references to us get released. This is because a component outside // of the managed code (ie. the window we are subclassing) still holds // a reference to us - just not a reference that the GC recognizes. _gcHandle = GCHandle.Alloc(this); }
internal HwndSubclass(HwndWrapperHook hook) { if(hook == null) { throw new ArgumentNullException("hook"); } _bond = Bond.Unattached; _hook = new WeakReference(hook); // Allocate a GC handle so that we won't be collected, even if all // references to us get released. This is because a component outside // of the managed code (ie. the window we are subclassing) still holds // a reference to us - just not a reference that the GC recognizes. _gcHandle = GCHandle.Alloc(this); }
///<summary> /// Construtor that takes a ActionQueue that it will be used to pull all the action /// that are going to be executed ///</summary> internal Win32AsyncActionsManager(ActionsQueue queue) { if (queue == null) { throw new ArgumentNullException("the ActionQueue cannot be null"); } if (queue.AmountTestCases <= 0) { throw new InvalidOperationException("The queue doesn't have any items"); } _queue = queue; _hwnd = new HwndWrapper(0, 0, 0, 0, 0, 0, 0, "", NativeConstants.HWND_MESSAGE, null); _hwndWrapperHook = new HwndWrapperHook(_hwndHook); _hwnd.AddHook(_hwndWrapperHook); }
private object DispatcherCallbackOperation(object o) { DispatcherOperationCallbackParameter param = (DispatcherOperationCallbackParameter)o; param.handled = false; param.retVal = IntPtr.Zero; if (_bond == Bond.Attached) { HwndWrapperHook hook = _hook.Target as HwndWrapperHook; if (hook != null) { // make the call param.retVal = hook(param.hwnd, param.msg, param.wParam, param.lParam, ref param.handled); } } return(param); }
private object DispatcherCallbackOperation(object o) { //extract parameters object[] args = (object[])o; IntPtr hwnd = (IntPtr)args[0]; Int32 msg = (Int32)args[1]; IntPtr wParam = (IntPtr)args[2]; IntPtr lParam = (IntPtr)args[3]; bool handled = false; IntPtr retval = IntPtr.Zero; // make the call HwndWrapperHook hook = _hook.Target as HwndWrapperHook; if (_bond == Bond.Attached && hook != null) { retval = hook(hwnd, msg, wParam, lParam, ref handled); } return(new object[] { retval, handled }); }
private static void EnsureResourceChangeListener() { // Create a new notify window if we haven't already created one for this thread. if (_hwndNotify == null) { // Create a top-level, invisible window so we can get the WM_THEMECHANGE notification // and for HwndHost to park non-visible HwndHosts. HwndWrapper hwndNotify; hwndNotify = new HwndWrapper(0, NativeMethods.WS_POPUP|NativeMethods.WS_DISABLED, 0, 0, 0, 0, 0, "SystemResourceNotifyWindow", IntPtr.Zero, null); _hwndNotify = new SecurityCriticalDataClass<HwndWrapper>(hwndNotify); _hwndNotify.Value.Dispatcher.ShutdownFinished += OnShutdownFinished; _hwndNotifyHook = new HwndWrapperHook(SystemThemeFilterMessage); _hwndNotify.Value.AddHook(_hwndNotifyHook); } }
private void SetUpInputHooks() { IKeyboardInputSink sink; new UIPermission(PermissionState.Unrestricted).Assert(); //BlessedAssert try { _inputPostFilter = new HwndWrapperHook(BrowserInteropHelper.PostFilterInput); HwndSource hwndSource = base.HwndSourceWindow; hwndSource.HwndWrapper.AddHookLast(_inputPostFilter); sink = (IKeyboardInputSink)hwndSource; } finally { UIPermission.RevertAll(); } new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); //BlessedAssert try { Debug.Assert(sink.KeyboardInputSite == null); sink.KeyboardInputSite = new KeyInputSite(new SecurityCriticalData<IKeyboardInputSink>(sink)); } finally { SecurityPermission.RevertAll(); } }
private void EnsureHwndSource() { // We don't support Activate, Deactivate, and SessionEnding // events for browser hosted scenarios thus don't create // this HwndSource if BrowserCallbackServices is valid if (BrowserCallbackServices == null && _parkingHwnd == null) { // _appFilterHook needs to be member variable otherwise // it is GC'ed and we don't get messages from HwndWrapper // (HwndWrapper keeps a WeakReference to the hook) _appFilterHook = new HwndWrapperHook(AppFilterMessage); HwndWrapperHook[] wrapperHooks = {_appFilterHook}; _parkingHwnd = new HwndWrapper( 0, 0, 0, 0, 0, 0, 0, "", IntPtr.Zero, wrapperHooks); } }
internal void AddHookLast(HwndWrapperHook hook) { if(_hooks == null) { _hooks = new SecurityCriticalDataClass<WeakReferenceList>(new WeakReferenceList()); } _hooks.Value.Add(hook); }
private Dispatcher() { _queue = new PriorityQueue<DispatcherOperation>(); _tlsDispatcher = this; // use TLS for ownership only _dispatcherThread = Thread.CurrentThread; // Add ourselves to the map of dispatchers to threads. lock(_globalLock) { _dispatchers.Add(new WeakReference(this)); } _unhandledExceptionEventArgs = new DispatcherUnhandledExceptionEventArgs(this); _exceptionFilterEventArgs = new DispatcherUnhandledExceptionFilterEventArgs(this); _dispatcherSynchronizationContext = new DispatcherSynchronizationContext(this); // Create the message-only window we use to receive messages // that tell us to process the queue. MessageOnlyHwndWrapper window = new MessageOnlyHwndWrapper(); _window = new SecurityCriticalData<MessageOnlyHwndWrapper>( window ); _hook = new HwndWrapperHook(WndProcHook); _window.Value.AddHook(_hook); }
public HwndWrapper( int classStyle, int style, int exStyle, int x, int y, int width, int height, string name, IntPtr parent, HwndWrapperHook[] hooks) { // First, add the set of hooks. This allows the hooks to receive the // messages sent to the window very early in the process. if (hooks != null) { for (int i = 0, iEnd = hooks.Length; i < iEnd; i++) { if (null != hooks[i]) { AddHook(hooks[i]); } } } _wndProc = new HwndWrapperHook(WndProc); // We create the HwndSubclass object so that we can use its // window proc directly. We will not be "subclassing" the // window we create. HwndSubclass hwndSubclass = new HwndSubclass(_wndProc); // Register a unique window class for this instance. Random r = new Random(unchecked ((int)DateTime.Now.Ticks)); NativeStructs.WNDCLASSEX_D wc_d = new NativeStructs.WNDCLASSEX_D(); NativeStructs.WNDCLASSEX_I wc_i = new NativeStructs.WNDCLASSEX_I(); IntPtr hInstance = NativeMethods.GetModuleHandle(null); IntPtr atom; string className = ""; do { // Create a suitable unique class name. atom = IntPtr.Zero; // The class name is a concat of AppName, ThreadName, and RandomNumber. // Register will fail if the string gets over 255 in length. // So limit each part to a reasonable amount. string appName; if (null != AppDomain.CurrentDomain.FriendlyName && 128 <= AppDomain.CurrentDomain.FriendlyName.Length) { appName = AppDomain.CurrentDomain.FriendlyName.Substring(0, 128); } else { appName = AppDomain.CurrentDomain.FriendlyName; } string threadName; if (null != Thread.CurrentThread.Name && 64 <= Thread.CurrentThread.Name.Length) { threadName = Thread.CurrentThread.Name.Substring(0, 64); } else { threadName = Thread.CurrentThread.Name; } className = String.Format(CultureInfo.InvariantCulture, "HwndWrapper[{0};{1};{2}]", appName, threadName, r.Next().ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); // Make sure the class name hasn't been used already. if (!NativeMethods.GetClassInfoEx(hInstance, className, wc_i)) { wc_d.cbSize = Marshal.SizeOf(typeof(NativeStructs.WNDCLASSEX_D)); wc_d.style = classStyle; wc_d.lpfnWndProc = new NativeStructs.WndProc(hwndSubclass.SubclassWndProc); wc_d.cbClsExtra = 0; wc_d.cbWndExtra = 0; wc_d.hInstance = hInstance; wc_d.hIcon = IntPtr.Zero; wc_d.hCursor = IntPtr.Zero; wc_d.hbrBackground = IntPtr.Zero; wc_d.lpszMenuName = ""; wc_d.lpszClassName = className; wc_d.hIconSm = IntPtr.Zero; // Register the unique class for this instance. // // Note that it might still be possible that a class with // this name will be registered between our previous // check and this call to RegisterClassEx(), so we also // must catch the exception that might be thrown. // // Note that under stress we saw an exception that we // think was due to this call to RegisterClassEx. We had // a try/catch block around this call, but it was deemed // to be an FxCop violation, so I removed it. atom = NativeMethods.RegisterClassEx(wc_d); // Clean up potentially bogus extra bits in the return value. //atom = (IntPtr)((uint)(atom) & 0xffff); } } while (atom == IntPtr.Zero); // call CreateWindow _isInCreateWindow = true; _handle = NativeMethods.CreateWindowEx(exStyle, className, name, style, x, y, width, height, parent, IntPtr.Zero, IntPtr.Zero, 0); int Win32Err = Marshal.GetLastWin32Error(); // Dance around FxCop _isInCreateWindow = false; if (_handle == IntPtr.Zero) { // Because the HwndSubclass is pinned, but the HWND creation failed, // we need to manually clean it up. hwndSubclass.Dispose(); throw new System.ComponentModel.Win32Exception(Win32Err); } }
public HwndWrapper( int classStyle, int style, int exStyle, int x, int y, int width, int height, string name, IntPtr parent, HwndWrapperHook[] hooks) { _ownerThreadID = new SecurityCriticalDataForSet<int>(Thread.CurrentThread.ManagedThreadId); // First, add the set of hooks. This allows the hooks to receive the // messages sent to the window very early in the process. if(hooks != null) { for(int i = 0, iEnd = hooks.Length; i < iEnd; i++) { if(null != hooks[i]) AddHook(hooks[i]); } } _wndProc = new SecurityCriticalData<HwndWrapperHook>(new HwndWrapperHook(WndProc)); // We create the HwndSubclass object so that we can use its // window proc directly. We will not be "subclassing" the // window we create. HwndSubclass hwndSubclass = new HwndSubclass(_wndProc.Value); // Register a unique window class for this instance. NativeMethods.WNDCLASSEX_D wc_d = new NativeMethods.WNDCLASSEX_D(); IntPtr hNullBrush = UnsafeNativeMethods.CriticalGetStockObject(NativeMethods.NULL_BRUSH); if (hNullBrush == IntPtr.Zero) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } IntPtr hInstance = UnsafeNativeMethods.GetModuleHandle( null ); // We need to keep the Delegate object alive through the call to CreateWindowEx(). // Subclass.WndProc will install a better delegate (to the same function) when it // processes the first message. // But this first delegate needs be held alive until then. NativeMethods.WndProc initialWndProc = new NativeMethods.WndProc(hwndSubclass.SubclassWndProc); // The class name is a concat of AppName, ThreadName, and RandomNumber. // Register will fail if the string gets over 255 in length. // So limit each part to a reasonable amount. string appName; if(null != AppDomain.CurrentDomain.FriendlyName && 128 <= AppDomain.CurrentDomain.FriendlyName.Length) appName = AppDomain.CurrentDomain.FriendlyName.Substring(0, 128); else appName = AppDomain.CurrentDomain.FriendlyName; string threadName; if(null != Thread.CurrentThread.Name && 64 <= Thread.CurrentThread.Name.Length) threadName = Thread.CurrentThread.Name.Substring(0, 64); else threadName = Thread.CurrentThread.Name; // Create a suitable unique class name. _classAtom = 0; string randomName = Guid.NewGuid().ToString(); string className = String.Format(CultureInfo.InvariantCulture, "HwndWrapper[{0};{1};{2}]", appName, threadName, randomName); wc_d.cbSize = Marshal.SizeOf(typeof(NativeMethods.WNDCLASSEX_D)); wc_d.style = classStyle; wc_d.lpfnWndProc = initialWndProc; wc_d.cbClsExtra = 0; wc_d.cbWndExtra = 0; wc_d.hInstance = hInstance; wc_d.hIcon = IntPtr.Zero; wc_d.hCursor = IntPtr.Zero; wc_d.hbrBackground = hNullBrush; wc_d.lpszMenuName = ""; wc_d.lpszClassName = className; wc_d.hIconSm = IntPtr.Zero; // Register the unique class for this instance. // Note we use a GUID in the name so we are confident that // the class name should be unique. And RegisterClassEx won't // fail (for that reason). _classAtom = UnsafeNativeMethods.RegisterClassEx(wc_d); // call CreateWindow _isInCreateWindow = true; try { _handle = new SecurityCriticalDataClass<IntPtr>(UnsafeNativeMethods.CreateWindowEx(exStyle, className, name, style, x, y, width, height, new HandleRef(null,parent), new HandleRef(null,IntPtr.Zero), new HandleRef(null,IntPtr.Zero), null)); } finally { _isInCreateWindow = false; if(_handle == null || _handle.Value == IntPtr.Zero) { new UIPermission(UIPermissionWindow.AllWindows).Assert(); //BlessedAssert to call Dispose try { // Because the HwndSubclass is pinned, but the HWND creation failed, // we need to manually clean it up. hwndSubclass.Dispose(); } finally { CodeAccessPermission.RevertAssert(); } } } GC.KeepAlive(initialWndProc); }
private void Initialize(HwndSourceParameters parameters) { _mouse = new SecurityCriticalDataClass<HwndMouseInputProvider>(new HwndMouseInputProvider(this)); _keyboard = new SecurityCriticalDataClass<HwndKeyboardInputProvider>(new HwndKeyboardInputProvider(this)); _layoutHook = new HwndWrapperHook(LayoutFilterMessage); _inputHook = new HwndWrapperHook(InputFilterMessage); _hwndTargetHook = new HwndWrapperHook(HwndTargetFilterMessage); _publicHook = new HwndWrapperHook(PublicHooksFilterMessage); // When processing WM_SIZE, LayoutFilterMessage must be invoked before // HwndTargetFilterMessage. This way layout will be updated before resizing // HwndTarget, resulting in single render per resize. This means that // layout hook should appear before HwndTarget hook in the wrapper hooks // list. If this is done the other way around, first HwndTarget resize will // force re-render, then layout will be updated according to the new size, // scheduling another render. HwndWrapperHook[] wrapperHooks = { _hwndTargetHook, _layoutHook, _inputHook, null }; if (null != parameters.HwndSourceHook) { // In case there's more than one delegate, add these to the event storage backwards // so they'll get invoked in the expected order. Delegate[] handlers = parameters.HwndSourceHook.GetInvocationList(); for (int i = handlers.Length -1; i >= 0; --i) { _hooks += (HwndSourceHook)handlers[i]; } wrapperHooks[3] = _publicHook; } _restoreFocusMode = parameters.RestoreFocusMode; _acquireHwndFocusInMenuMode = parameters.AcquireHwndFocusInMenuMode; // A window must be marked WS_EX_LAYERED if (and only if): // 1) it is not a child window // -- AND -- // 2) a color-key is specified // 3) or an opacity other than 1.0 is specified // 4) or per-pixel alpha is requested. if((parameters.WindowStyle & NativeMethods.WS_CHILD) == 0 && ( //parameters.ColorKey != null || //!MS.Internal.DoubleUtil.AreClose(parameters.Opacity, 1.0) || parameters.UsesPerPixelOpacity)) { parameters.ExtendedWindowStyle |= NativeMethods.WS_EX_LAYERED; } else { parameters.ExtendedWindowStyle &= (~NativeMethods.WS_EX_LAYERED); } _constructionParameters = parameters; _hwndWrapper = new HwndWrapper(parameters.WindowClassStyle, parameters.WindowStyle, parameters.ExtendedWindowStyle, parameters.PositionX, parameters.PositionY, parameters.Width, parameters.Height, parameters.WindowName, parameters.ParentWindow, wrapperHooks); _hwndTarget = new HwndTarget(_hwndWrapper.Handle); //_hwndTarget.ColorKey = parameters.ColorKey; //_hwndTarget.Opacity = parameters.Opacity; _hwndTarget.UsesPerPixelOpacity = parameters.UsesPerPixelOpacity; if(_hwndTarget.UsesPerPixelOpacity) { _hwndTarget.BackgroundColor = Colors.Transparent; // Prevent this window from being themed. UnsafeNativeMethods.CriticalSetWindowTheme(new HandleRef(this, _hwndWrapper.Handle), "", ""); } _constructionParameters = null; if (!parameters.HasAssignedSize) _sizeToContent = SizeToContent.WidthAndHeight; _adjustSizingForNonClientArea = parameters.AdjustSizingForNonClientArea; _treatAncestorsAsNonClientArea = parameters.TreatAncestorsAsNonClientArea; // Listen to the UIContext.Disposed event so we can clean up. // The HwndTarget cannot work without a MediaContext which // is disposed when the UIContext is disposed. So we need to // dispose the HwndTarget and also never use it again (to // paint or process input). The easiest way to do this is to just // dispose the HwndSource at the same time. _weakShutdownHandler = new WeakEventDispatcherShutdown(this, this.Dispatcher); // Listen to the HwndWrapper.Disposed event so we can clean up. // The HwndTarget cannot work without a live HWND, and since // the HwndSource represents an HWND, we make sure we dispose // ourselves if the HWND is destroyed out from underneath us. _hwndWrapper.Disposed += new EventHandler(OnHwndDisposed); _stylus = new SecurityCriticalDataClass<HwndStylusInputProvider>(new HwndStylusInputProvider(this)); // WM_APPCOMMAND events are handled thru this. _appCommand = new SecurityCriticalDataClass<HwndAppCommandInputProvider>(new HwndAppCommandInputProvider(this)); // Register the top level source with the ComponentDispatcher. if (parameters.TreatAsInputRoot) { _weakPreprocessMessageHandler = new WeakEventPreprocessMessage(this, false); } AddSource(); // Register dropable window. // The checking CallerHasPermissionWithAppDomainOptimization will call RegisterDropTarget // safely without the security exception in case of no unmanaged code permission. // So RegisterDropTarget will be called safely in case of having the unmanged code permission. // Otherwise, the security exception cause System.Printing to be instatiated which will // load system.drawing module. if (_hwndWrapper.Handle != IntPtr.Zero && SecurityHelper.CallerHasPermissionWithAppDomainOptimization(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode))) { // This call is safe since DragDrop.RegisterDropTarget is checking the unmanged // code permission. DragDrop.RegisterDropTarget(_hwndWrapper.Handle); _registeredDropTargetCount++; } }
public void AddHook(HwndWrapperHook hook) { //VerifyAccess(); if(_hooks == null) { _hooks = new SecurityCriticalDataClass<WeakReferenceList>(new WeakReferenceList()); } _hooks.Value.Insert(0, hook); }
private void Initialize( bool fTrusted ) { _fTrusted = new SecurityCriticalDataForSet<bool> ( fTrusted ) ; _hwndSubclassHook = new HwndWrapperHook(SubclassWndProc); _handlerLayoutUpdated = new EventHandler(OnLayoutUpdated); _handlerEnabledChanged = new DependencyPropertyChangedEventHandler(OnEnabledChanged); _handlerVisibleChanged = new DependencyPropertyChangedEventHandler(OnVisibleChanged); PresentationSource.AddSourceChangedHandler(this, new SourceChangedEventHandler(OnSourceChanged)); _weakEventDispatcherShutdown = new WeakEventDispatcherShutdown(this, this.Dispatcher); }
public NotificationWindowHelper() { // Check for Vista or newer is needed for RegisterPowerSettingNotification. // This check needs to rescoped to the said method call, if other // notifications are implemented. if (Utilities.IsOSVistaOrNewer) { // _notificationHook needs to be member variable otherwise // it is GC'ed and we don't get messages from HwndWrapper // (HwndWrapper keeps a WeakReference to the hook) _notificationHook = new HwndWrapperHook(NotificationFilterMessage); HwndWrapperHook[] wrapperHooks = { _notificationHook }; _notificationHwnd = new HwndWrapper( 0, 0, 0, 0, 0, 0, 0, "", IntPtr.Zero, wrapperHooks); Guid monitorGuid = new Guid(NativeMethods.GUID_MONITOR_POWER_ON.ToByteArray()); unsafe { _hPowerNotify = UnsafeNativeMethods.RegisterPowerSettingNotification(_notificationHwnd.Handle, &monitorGuid, 0); } } }