public HorizontalMouseScrollHelper(ScrollViewer scrollviewer, DependencyObject d)
 {
     scrollViewer = scrollviewer;
     source = (HwndSource)PresentationSource.FromDependencyObject(d);
     if (source != null)
         source.AddHook(WindowProc);
 }
 protected override void OnSourceInitialized(EventArgs e)
 {
     _hwndSource = (HwndSource) PresentationSource.FromVisual(this);
     _hwndSource?.AddHook(WndProcHook);
     UpdateWindowStyle();
     base.OnSourceInitialized(e);
 }
Пример #3
0
 // Constructor
 public ClipboardListenerBasic(Window wnd,EventHandler handler=null)
 {
     WindowListener=wnd;
     Source=PresentationSource.FromVisual(wnd) as HwndSource;
     ClipboardUpdated=handler;
     Listening=false;
 }
Пример #4
0
		private void Initialize3D()
		{
			HwndSource hwnd = new HwndSource(0, 0, 0, 0, 0, "D3", IntPtr.Zero);

			pp.SwapEffect = SwapEffect.Discard;
			pp.DeviceWindowHandle = hwnd.Handle;
			pp.Windowed = true;
			pp.BackBufferWidth = (int)ActualWidth;
			pp.BackBufferHeight = (int)ActualHeight;
			pp.BackBufferFormat = Format.X8R8G8B8;

			try
			{
				var direct3DEx = new Direct3DEx();
				direct3D = direct3DEx;
				device = new DeviceEx(direct3DEx, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, pp);
			}
			catch
			{
				direct3D = new Direct3D();
				device = new Device(direct3D, 0, DeviceType.Hardware, hwnd.Handle, CreateFlags.HardwareVertexProcessing, pp);
			}

			System.Windows.Media.CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
		}
 protected void OnLoaded(object sender, EventArgs e)
 {
     WindowInteropHelper helper = new WindowInteropHelper(this);
     _hwndSource = HwndSource.FromHwnd(helper.Handle);
     _wndProcHandler = new HwndSourceHook(HookHandler);
     _hwndSource.AddHook(_wndProcHandler);
 }
Пример #6
0
 protected override void OnClosed(EventArgs e)
 {
     _source.RemoveHook(HwndHook);
     _source = null;
     UnregisterHotKey();
     base.OnClosed(e);
 }
Пример #7
0
 //private Window window;
 //stack overflow http://stackoverflow.com/questions/2450373/set-global-hotkeys-using-c-sharp
 //private class Window : NativeWindow, IDisposable
 //{
 //    private static int WM_HOTKEY = 0x0312;
 //    private IHotKeyOwner owner;
 //    public Window(IHotKeyOwner owner)
 //    {
 //        this.owner = owner;
 //        // create the handle for the window.
 //        this.CreateHandle(new CreateParams());
 //    }
 //    /// <summary>
 //    /// Overridden to get the notifications.
 //    /// </summary>
 //    /// <param name="m"></param>
 //    protected override void WndProc(ref Message m)
 //    {
 //        base.WndProc(ref m);
 //        // check if we got a hot key pressed.
 //        if (m.Msg == WM_HOTKEY)
 //        {
 //            MessageBox.Show("asdasd");
 //            // get the keys.
 //            Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
 //            ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);
 //            owner.HotKeyPressed(0);
 //        }
 //    }
 //    #region IDisposable Members
 //    public void Dispose()
 //    {
 //        this.DestroyHandle();
 //    }
 //    #endregion
 //}
 public HotKeyManager(IHotKeyOwner owner, IntPtr handle)
 {
     this.owner = owner;
     this.hook = new HwndSourceHook(WndProc);
     this.hwndsource = HwndSource.FromHwnd(handle);
     hwndsource.AddHook(hook);
 }
 private void StartListeningToClipboard()
 {
     var lWindowInteropHelper = new WindowInteropHelper(this);
     _HWndSource = HwndSource.FromHwnd(lWindowInteropHelper.Handle);
     _HWndSource.AddHook(WinProc);
     _HWndNextViewer = SetClipboardViewer(_HWndSource.Handle); // set this window as a viewer
 } //
Пример #9
0
        internal HwndStylusInputProvider(HwndSource source)
        {
            InputManager inputManager = InputManager.Current;
            StylusLogic stylusLogic = inputManager.StylusLogic;

            IntPtr sourceHandle;

            (new UIPermission(PermissionState.Unrestricted)).Assert();
            try //Blessed Assert this is for RegisterInputManager and RegisterHwndforinput
            {
                // Register ourselves as an input provider with the input manager.
                _site = new SecurityCriticalDataClass<InputProviderSite>(inputManager.RegisterInputProvider(this));

                sourceHandle = source.Handle;
            }
            finally
            {
                UIPermission.RevertAssert();
            }

            stylusLogic.RegisterHwndForInput(inputManager, source);
            _source = new SecurityCriticalDataClass<HwndSource>(source);
            _stylusLogic = new SecurityCriticalDataClass<StylusLogic>(stylusLogic);

            // Enables multi-touch input
            UnsafeNativeMethods.SetProp(new HandleRef(this, sourceHandle), "MicrosoftTabletPenServiceProperty", new HandleRef(null, new IntPtr(MultiTouchEnabledFlag)));
        }
Пример #10
0
    private void ShadowedWindow_OnLoaded(object sender, RoutedEventArgs e)
    {
      hwndSource = PresentationSource.FromVisual((Visual) sender) as HwndSource;

      if (hwndSource != null)
        hwndSource.AddHook(WndProc);
    }
        public void Show(Int32Rect rpRect)
        {
            var rMainWindowHandle = new WindowInteropHelper(App.Current.MainWindow).Handle;

            if (r_HwndSource == null)
            {
                var rParam = new HwndSourceParameters(nameof(ScreenshotToolOverlayWindow))
                {
                    Width = 0,
                    Height = 0,
                    PositionX = 0,
                    PositionY = 0,
                    WindowStyle = 0,
                    UsesPerPixelOpacity = true,
                    HwndSourceHook = WndProc,
                    ParentWindow = rMainWindowHandle,
                };

                r_HwndSource = new HwndSource(rParam) { SizeToContent = SizeToContent.Manual, RootVisual = this };
            }

            var rBrowserWindowHandle = ServiceManager.GetService<IBrowserService>().Handle;

            NativeStructs.RECT rBrowserWindowRect;
            NativeMethods.User32.GetWindowRect(rBrowserWindowHandle, out rBrowserWindowRect);

            var rHorizontalRatio = rBrowserWindowRect.Width / GameConstants.GameWidth;
            var rVerticalRatio = rBrowserWindowRect.Height / GameConstants.GameHeight;
            rpRect.X = (int)(rpRect.X * rHorizontalRatio);
            rpRect.Y = (int)(rpRect.Y * rVerticalRatio);
            rpRect.Width = (int)(rpRect.Width * rHorizontalRatio);
            rpRect.Height = (int)(rpRect.Height * rVerticalRatio);

            NativeMethods.User32.SetWindowPos(r_HwndSource.Handle, IntPtr.Zero, rBrowserWindowRect.Left + rpRect.X, rBrowserWindowRect.Top + rpRect.Y, rpRect.Width, rpRect.Height, NativeEnums.SetWindowPosition.SWP_NOZORDER | NativeEnums.SetWindowPosition.SWP_NOACTIVATE | NativeEnums.SetWindowPosition.SWP_SHOWWINDOW);
        }
Пример #12
0
 public HotkeyManager(Window window)
 {
     source = (HwndSource)PresentationSource.FromVisual(window);
     hook = new HwndSourceHook(WndProc);
     source.AddHook(hook);
     ids = new List<int>();
 }
Пример #13
0
 /// <summary>
 /// ClipBoardWatcherクラスを初期化して
 /// クリップボードビューアチェインに登録します。
 /// 使用後は必ずDispose()メソッドを呼び出して下さい。
 /// </summary>
 public ClipboardWatcher(IntPtr handle)
 {
     this.hwndSource = HwndSource.FromHwnd(handle);
     this.hwndSource.AddHook(this.WndProc);
     this.handle = handle;
     this.nextHandle = SetClipboardViewer(this.handle);
 }
Пример #14
0
        public Recorder(string fileName, 
            FourCC codec, int quality, 
            int audioSourceIndex, SupportedWaveFormat audioWaveFormat, bool encodeAudio, int audioBitRate)
        {
            System.Windows.Media.Matrix toDevice;
            using (var source = new HwndSource(new HwndSourceParameters()))
            {
                toDevice = source.CompositionTarget.TransformToDevice;
            }

            screenWidth = (int)Math.Round(SystemParameters.PrimaryScreenWidth * toDevice.M11);
            screenHeight = (int)Math.Round(SystemParameters.PrimaryScreenHeight * toDevice.M22);

            // Create AVI writer and specify FPS
            writer = new AviWriter(fileName)
            {
                FramesPerSecond = 10,
                EmitIndex1 = true,
            };

            // Create video stream
            videoStream = CreateVideoStream(codec, quality);
            // Set only name. Other properties were when creating stream,
            // either explicitly by arguments or implicitly by the encoder used
            videoStream.Name = "Screencast";

            if (audioSourceIndex >= 0)
            {
                var waveFormat = ToWaveFormat(audioWaveFormat);

                audioStream = CreateAudioStream(waveFormat, encodeAudio, audioBitRate);
                // Set only name. Other properties were when creating stream,
                // either explicitly by arguments or implicitly by the encoder used
                audioStream.Name = "Voice";

                audioSource = new WaveInEvent
                {
                    DeviceNumber = audioSourceIndex,
                    WaveFormat = waveFormat,
                    // Buffer size to store duration of 1 frame
                    BufferMilliseconds = (int)Math.Ceiling(1000 / writer.FramesPerSecond),
                    NumberOfBuffers = 3,
                };
                audioSource.DataAvailable += audioSource_DataAvailable;
            }

            screenThread = new Thread(RecordScreen)
            {
                Name = typeof(Recorder).Name + ".RecordScreen",
                IsBackground = true
            };

            if (audioSource != null)
            {
                videoFrameWritten.Set();
                audioBlockWritten.Reset();
                audioSource.StartRecording();
            }
            screenThread.Start();
        }
Пример #15
0
		private void Start()
		{
			if (hwndSource != null)
				return;


			var window = Application.Current.Windows[0];
			Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() =>
			{

				if (!window.IsInitialized)
					window.SourceInitialized += (sender, args) =>
					{
						hwndSource = HwndSource.FromHwnd(new WindowInteropHelper(window).Handle);
						hwndSource.AddHook(WndProc);
					};
				else
				{
					hwndSource = HwndSource.FromHwnd(new WindowInteropHelper(window).Handle);
					hwndSource.AddHook(WndProc);
				}
			}));



		}
Пример #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HotKeyManager"/> class.
        /// </summary>
        public HotKeyManager()
        {
            _windowHandleSource = new HwndSource(new HwndSourceParameters());
            _windowHandleSource.AddHook(messagesHandler);

            _registered = new Dictionary<HotKey, int>();
        }
Пример #17
0
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            var mode = e.Args.Any() ? e.Args[0] : "/s";

            // Preview mode--display in little window in Screen Saver dialog
            // (Not invoked with Preview button, which runs Screen Saver in
            // normal /s mode).
            if (mode.ToLower().StartsWith("/p"))
            {
                m_winSaver = new MainWindow();

                Int32 previewHandle = Convert.ToInt32(e.Args[1]);
                //WindowInteropHelper interopWin1 = new WindowInteropHelper(win);
                //interopWin1.Owner = new IntPtr(previewHandle);

                var pPreviewHnd = new IntPtr(previewHandle);

                var lpRect = new RECT();
                Win32API.GetClientRect(pPreviewHnd, ref lpRect);

                var sourceParams = new HwndSourceParameters("sourceParams")
                {
                    PositionX = 0,
                    PositionY = 0,
                    Height = lpRect.Bottom - lpRect.Top,
                    Width = lpRect.Right - lpRect.Left,
                    ParentWindow = pPreviewHnd,
                    WindowStyle = (int)(WindowStyles.WS_VISIBLE | WindowStyles.WS_CHILD | WindowStyles.WS_CLIPCHILDREN)
                };

                m_winWpfContent = new HwndSource(sourceParams);
                m_winWpfContent.Disposed += winWPFContent_Disposed;
                m_winWpfContent.RootVisual = m_winSaver.Grid;
                // ReSharper disable once CSharpWarnings::CS4014
                m_winSaver.StartAnimation();
            }

            // Normal screensaver mode.  Either screen saver kicked in normally,
            // or was launched from Preview button
            else if (mode.ToLower().StartsWith("/s"))
            {
                var win = new MainWindow { WindowState = WindowState.Maximized };
                win.Show();
            }

            // Config mode, launched from Settings button in screen saver dialog
            else if (mode.ToLower().StartsWith("/c"))
            {
                var win = new SettingsWindow();
                win.Show();
            }

            // If not running in one of the sanctioned modes, shut down the app
            // immediately (because we don't have a GUI).
            else
            {
                Current.Shutdown();
            }
        }
Пример #18
0
 protected override void OnSourceInitialized(EventArgs e)
 {
     base.OnSourceInitialized(e);
     var helper = new WindowInteropHelper(this);
     _source = HwndSource.FromHwnd(helper.Handle);
     _source.AddHook(HwndHook);
     RegisterHotKey();
 }
Пример #19
0
 protected override sealed void OnSourceDisconnected(HwndSource disconnectedSource)
 {
     var window = disconnectedSource.RootVisual as Window;
     if (window != null)
     {
         OnWindowDisconnected(window);
     }
 }
Пример #20
0
        private void InitCBViewer()
        {
            WindowInteropHelper wih = new WindowInteropHelper(this);
            hWndSource = HwndSource.FromHwnd(wih.Handle);

            hWndSource.AddHook(this.WndProc);   // start processing window messages
            hWndNextViewer = Win32.SetClipboardViewer(hWndSource.Handle);   // set this window as a viewer
        }
Пример #21
0
 public static bool SetCompositionFont(HwndSource source, IntPtr hIMC, TextArea textArea)
 {
     if (textArea == null)
         throw new ArgumentNullException("textArea");
     //			LOGFONT font = new LOGFONT();
     //			ImmGetCompositionFont(hIMC, out font);
     return false;
 }
Пример #22
0
 public BaseWindow()
 {
     base.SourceInitialized += delegate(object sender, System.EventArgs e)
     {
         this.hwndSource = (PresentationSource.FromVisual((Visual)sender) as HwndSource);
         this.hwndSource.AddHook(new HwndSourceHook(Win32Helper.WindowProc));
     };
 }
Пример #23
0
        RegionSelector()
        {
            InitializeComponent();

            Show();
            RegSelhWnd = (HwndSource)HwndSource.FromVisual(this);
            Hide();
        }
Пример #24
0
        public virtual void Close()
        {
            this.Source?.RemoveHook(this.WndProc);
            this.Source?.Dispose();
            this.Source = null;

            NativeMethods.CloseWindow(this.Handle);
        }
Пример #25
0
        public virtual void Close()
        {
            this.Source?.RemoveHook(this.WndProc);
            this.Source?.Dispose();
            this.Source = null;

            User32.CloseWindow(this.Handle);
        }
Пример #26
0
        public HwndPanningFeedback(HwndSource hwndSource) 
        {
            if (hwndSource == null) 
            { 
                throw new ArgumentNullException("hwndSource");
            } 

            _hwndSource = hwndSource;
        }
Пример #27
0
        private void RegisterHotKey()
        {
            IntPtr hwnd = new WindowInteropHelper(this).Handle;

            //获得消息源
            System.Windows.Interop.HwndSource source = System.Windows.Interop.HwndSource.FromHwnd(hwnd);

            source.AddHook(HotKeyHook);
        }
 private void AddHook(Visual window)
 {
     if (_hwndSource != null) return;
     _hwndSource = PresentationSource.FromVisual(window) as HwndSource;
     if (_hwndSource != null)
     {
         _hwndSource.AddHook(HwndSourceHook);
     }
 }
Пример #29
0
 public MessageWindow()
 {
     HwndSourceParameters sourceParams = new HwndSourceParameters()
     {
         ParentWindow = HWND_MESSAGE
     };
     Source = new HwndSource(sourceParams);
     Handle = Source.Handle;
 }
Пример #30
0
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            hWndSrc = PresentationSource.FromVisual(this) as HwndSource;
            DataContext = mainViewModel = new MainViewModel(this.Dispatcher, hWndSrc.Handle);
            hWndSrc.AddHook(mainViewModel.ApiInstance.WndProc);
            mainViewModel.ConnectToHost();
        }
Пример #31
0
 protected override void OnClosed(EventArgs e)
 {
     if (_hwndSource != null)
     {
         _hwndSource.Dispose();
         _hwndSource = null;
     }
     base.OnClosed(e);
 }
Пример #32
0
        //=============================================================================
        void OnSourceInitialized(object sender, EventArgs e)
        {
            System.Windows.Interop.HwndSource source = System.Windows.Interop.HwndSource.FromHwnd(new System.Windows.Interop.WindowInteropHelper(this).Handle);
            source.AddHook(new System.Windows.Interop.HwndSourceHook(WndProc));

            //
            m_WndHandle = new WindowInteropHelper(this).Handle;
            WindowsUtils.DisableMaximizeButton(m_WndHandle);
            WindowsUtils.EnableMinimizeButton(m_WndHandle);
        }
Пример #33
0
        //安装热键处理挂钩
        static private bool InstallHotKeyHook(HotKey hk)
        {
            if (hk.Window == null || hk.Handle == IntPtr.Zero)
            {
                return(false);
            }

            //获得消息源
            System.Windows.Interop.HwndSource source = System.Windows.Interop.HwndSource.FromHwnd(hk.Handle);
            if (source == null)
            {
                return(false);
            }

            //挂接事件
            source.AddHook(HotKey.HotKeyHook);
            return(true);
        }
Пример #34
0
 public bool InstallHotKeyHook(Window window)
 {
     if (window == null)
     {
         return(false);
     }
     System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(window);
     if (IntPtr.Zero == helper.Handle)
     {
         return(false);
     }
     System.Windows.Interop.HwndSource source = System.Windows.Interop.HwndSource.FromHwnd(helper.Handle);
     if (source == null)
     {
         return(false);
     }
     source.AddHook(this.HotKeyHook);
     return(true);
 }
Пример #35
0
        private static System.IntPtr WindowProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
            case 0x0024:
                WinInterop.HwndSource _win = WinInterop.HwndSource.FromHwnd(hwnd);
                Window _root = (Window)_win.RootVisual;

                //only
                if (_root.WindowState != WindowState.Maximized)
                {
                    break;
                }

                WmGetMinMaxInfo(hwnd, lParam);
                handled = true;
                break;
            }

            return((System.IntPtr) 0);
        }
Пример #36
0
        public static Size GetElementPixelSize(UIElement element)
        {
            Matrix transformToDevice;
            var    source = PresentationSource.FromVisual(element);

            if (source != null)
            {
                transformToDevice = source.CompositionTarget.TransformToDevice;
            }
            else
            {
                using (var source1 = new System.Windows.Interop.HwndSource(new System.Windows.Interop.HwndSourceParameters()))
                    transformToDevice = source1.CompositionTarget.TransformToDevice;
            }

            if (element.DesiredSize == new Size())
            {
                element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            }

            return((Size)transformToDevice.Transform((Vector)element.DesiredSize));
        }
Пример #37
0
 internal void RegisterWindowHandle(System.Windows.Interop.HwndSource hwndSource)
 {
     _hwndSource = hwndSource;
 }
Пример #38
0
        private void OnSetFocus(IntPtr hwnd)
        {
            // Normally we get WM_SETFOCUS only when _active is false.
            // Dev11 364494 revealed a situation where we get it when _active is true:
            //  1. Window contains a WindowsFormsHost, which contains a WF.TextBox that has focus
            //  2. User types Alt-Tab to switch to another app
            //  3. User types Alt-Tab again to return to this window
            // The ALT key sets _active to true, as we are processing keyboard input,
            // even though focus is in another window (the WF.TextBox).  But Alt-Tab
            // sends focus to another app, and we don't get any messages (the WF.TextBox
            // gets WM_KILLFOCUS, but doesn't tell us about it).   Thus when focus
            // returns after the second Alt-Tab, _active is still true.
            //
            // We need to run the focus restoration logic in this case. To make that
            // happen, we set _active to false here.  This leaves _active in the
            // state we want, even if the code herein encounters errors/exceptions.
            // There may be other cases where _active is true here (we don't know of
            // any, but we cannot rule them out), but we believe that the code won't
            // do any harm.
            _active = false;

            if (!_active)
            {
                // There is a chance that external code called during the focus
                // changes below will dispose our window, causing _source to get
                // cleared.  We actually saw this in XDesProc (the Blend XAML
                // designer process) in 4.5 Beta, but never tracked down the culprit.
                // To be safe, we cache the member variable in a local variable
                // for use within this method.
                HwndSource thisSource = _source.Value;

                // Console.WriteLine("WM_SETFOCUS");

                ReportInput(hwnd,
                            InputMode.Foreground,
                            _msgTime,
                            RawKeyboardActions.Activate,
                            0,
                            false,
                            false,
                            0);

                // MITIGATION: KEYBOARD_STATE_OUT_OF_SYNC
                //
                // This is how we deal with the fact that Win32 sometimes sends
                // us a WM_SETFOCUS message BEFORE it has updated it's internal
                // internal keyboard state information.  When we get the
                // WM_SETFOCUS message, we activate the keyboard with the
                // keyboard state (even though it could be wrong).  Then when
                // we get the first "real" keyboard input event, we activate
                // the keyboard again, since Win32 will have updated the
                // keyboard state correctly by then.
                //
                _partialActive = true;

                if (!_acquiringFocusOurselves && thisSource.RestoreFocusMode == RestoreFocusMode.Auto)
                {
                    // Restore the keyboard focus to the child window or element that had
                    // the focus before we last lost Win32 focus.  If nothing
                    // had focus before, set it to null.
                    if (_restoreFocusWindow != IntPtr.Zero)
                    {
                        IntPtr hwndRestoreFocus = _restoreFocusWindow;
                        _restoreFocusWindow = IntPtr.Zero;

                        UnsafeNativeMethods.TrySetFocus(new HandleRef(this, hwndRestoreFocus), ref hwndRestoreFocus);
                    }
                    else
                    {
                        DependencyObject restoreFocusDO = _restoreFocus as DependencyObject;
                        _restoreFocus = null;

                        if (restoreFocusDO != null)
                        {
                            // Only restore focus to an element if that
                            // element still belongs to this HWND.
                            HwndSource hwndSource = PresentationSource.CriticalFromVisual(restoreFocusDO) as HwndSource;
                            if (hwndSource != thisSource)
                            {
                                restoreFocusDO = null;
                            }
                        }

                        // Try to restore focus to the last element that had focus.  Note
                        // that if restoreFocusDO is null, we will internally set focus
                        // to the root element.
                        Keyboard.Focus(restoreFocusDO as IInputElement);

                        // Lots of things can happen when setting focus to an element,
                        // including that element may set focus somewhere else, possibly
                        // even into another HWND.  However, if Win32 focus remains on
                        // this window, we do not allow the focused element to be in
                        // a different window.
                        IntPtr focus = UnsafeNativeMethods.GetFocus();
                        if (focus == thisSource.CriticalHandle)
                        {
                            restoreFocusDO = (DependencyObject)Keyboard.FocusedElement;
                            if (restoreFocusDO != null)
                            {
                                HwndSource hwndSource = PresentationSource.CriticalFromVisual(restoreFocusDO) as HwndSource;
                                if (hwndSource != thisSource)
                                {
                                    Keyboard.ClearFocus();
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #39
0
        internal IntPtr FilterMessage(IntPtr hwnd, WindowMessage message, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            IntPtr result = IntPtr.Zero;

            // It is possible to be re-entered during disposal.  Just return.
            if (null == _source || null == _source.Value)
            {
                return(result);
            }

            _msgTime = 0;
            try
            {
                _msgTime = SafeNativeMethods.GetMessageTime();
            }
            catch (System.ComponentModel.Win32Exception)
            {
                System.Diagnostics.Debug.WriteLine("HwndKeyboardInputProvider: GetMessageTime failed!");
            }

            switch (message)
            {
            // WM_KEYDOWN is sent when a nonsystem key is pressed.
            // A nonsystem key is a key that is pressed when the ALT key
            // is not pressed.
            // WM_SYSKEYDOWN is sent when a system key is pressed.
            case WindowMessage.WM_SYSKEYDOWN:
            case WindowMessage.WM_KEYDOWN:
            {
                // If we have a IKeyboardInputSite, then we should have already
                // called ProcessKeyDown (from TranslateAccelerator)
                // But there are several paths (our message pump / app's message
                // pump) where we do (or don't) call through IKeyboardInputSink.
                // So the best way is to just check here if we already did it.
                if (_source.Value.IsRepeatedKeyboardMessage(hwnd, (int)message, wParam, lParam))
                {
                    break;
                }

                // We will use the current time before generating KeyDown events so we can filter
                // the later posted WM_CHAR.
                int currentTime = 0;
                try
                {
                    currentTime = SafeNativeMethods.GetTickCount();
                }
                catch (System.ComponentModel.Win32Exception)
                {
                    System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetTickCount failed!");
                }

                // MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS
                // In case a nested message pump is used before we return
                // from processing this message, we disable processing the
                // next WM_CHAR message because if the code pumps messages
                // it should really mark the message as handled.
                HwndSource._eatCharMessages = true;
                DispatcherOperation restoreCharMessages = Dispatcher.BeginInvoke(DispatcherPriority.Normal, new DispatcherOperationCallback(HwndSource.RestoreCharMessages), null);

                // Force the Dispatcher to post a new message to service any
                // pending operations, so that the operation we just posted
                // is guaranteed to get dispatched after any pending WM_CHAR
                // messages are dispatched.
                Dispatcher.CriticalRequestProcessing(true);

                MSG msg = new MSG(hwnd, (int)message, wParam, lParam, _msgTime, 0, 0);
                ProcessKeyAction(ref msg, ref handled);

                if (!handled)
                {
                    // MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS
                    // We did not handle the WM_KEYDOWN, so it is OK to process WM_CHAR messages.
                    // We can also abort the pending restore operation since we don't need it.
                    HwndSource._eatCharMessages = false;
                    restoreCharMessages.Abort();
                }

                // System.Console.WriteLine("KEYDOWN(message={0}, wParam={1})={2}", message, wParam, handled);
            }
            break;

            // WM_KEYUP is sent when a nonsystem key is released.
            // A nonsystem key is a key that is pressed when the ALT key
            // is not pressed.
            // WM_SYSKEYUP is sent when a system key is released.
            case WindowMessage.WM_SYSKEYUP:
            case WindowMessage.WM_KEYUP:
            {
                if (_source.Value.IsRepeatedKeyboardMessage(hwnd, (int)message, wParam, lParam))
                {
                    break;
                }

                MSG msg = new MSG(hwnd, (int)message, wParam, lParam, _msgTime, 0, 0);
                ProcessKeyAction(ref msg, ref handled);
                // System.Console.WriteLine("KEYUP  (message={0}, wParam={1})={2}", message, wParam, handled);
            }
            break;

            //

            case WindowMessage.WM_CHAR:
            case WindowMessage.WM_DEADCHAR:
            case WindowMessage.WM_SYSCHAR:
            case WindowMessage.WM_SYSDEADCHAR:
            {
                if (_source.Value.IsRepeatedKeyboardMessage(hwnd, (int)message, wParam, lParam))
                {
                    break;
                }

                // MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS
                if (HwndSource._eatCharMessages)
                {
                    break;
                }

                ProcessTextInputAction(hwnd, message, wParam, lParam, ref handled);
                // System.Console.WriteLine("CHAR(message={0}, wParam={1})={2}", message, wParam, handled);
            }
            break;

            case WindowMessage.WM_EXITMENULOOP:
            case WindowMessage.WM_EXITSIZEMOVE:
            {
                // MITIGATION: KEYBOARD_STATE_OUT_OF_SYNC
                //
                // Avalon relies on keeping it's copy of the keyboard
                // state.  This is for a number of reasons, including that
                // we need to be able to give this state to worker threads.
                //
                // There are a number of cases where Win32 eats the
                // keyboard messages, and this can cause our keyboard
                // state to become stale.  Obviously this can happen when
                // another app is in the foreground, but we handle that
                // by re-synching our keyboard state when we get focus.
                //
                // Other times are when Win32 enters a nested loop.  While
                // any one could enter a nested loop at any time for any
                // reason, Win32 is nice enough to let us know when it is
                // finished with the two common loops: menus and sizing.
                // We re-sync our keyboard device in response to these.
                //
                if (_active)
                {
                    _partialActive = true;

                    ReportInput(hwnd,
                                InputMode.Foreground,
                                _msgTime,
                                RawKeyboardActions.Activate,
                                0,
                                false,
                                false,
                                0);
                }
            }
            break;

            // WM_SETFOCUS is sent immediately after focus is granted.
            // This is our clue that the keyboard is active.
            case WindowMessage.WM_SETFOCUS:
            {
                OnSetFocus(hwnd);

                handled = true;
            }
            break;

            // WM_KILLFOCUS is sent immediately before focus is removed.
            // This is our clue that the keyboard is inactive.
            case WindowMessage.WM_KILLFOCUS:
            {
                if (_active && wParam != _source.Value.CriticalHandle)
                {
                    // Console.WriteLine("WM_KILLFOCUS");

                    if (_source.Value.RestoreFocusMode == RestoreFocusMode.Auto)
                    {
                        // when the window that's acquiring focus (wParam) is
                        // a descendant of our window, remember the immediate
                        // child so that we can restore focus to it.
                        _restoreFocusWindow = GetImmediateChildFor((IntPtr)wParam, _source.Value.CriticalHandle);

                        _restoreFocus = null;

                        // If we aren't restoring focus to a child window,
                        // then restore focus to the element that currently
                        // has WPF keyboard focus if it is directly in this
                        // HwndSource.
                        if (_restoreFocusWindow == IntPtr.Zero)
                        {
                            DependencyObject focusedDO = Keyboard.FocusedElement as DependencyObject;
                            if (focusedDO != null)
                            {
                                HwndSource hwndSource = PresentationSource.CriticalFromVisual(focusedDO) as HwndSource;
                                if (hwndSource == _source.Value)
                                {
                                    _restoreFocus = focusedDO as IInputElement;
                                }
                            }
                        }
                    }

                    PossiblyDeactivate((IntPtr)wParam);
                }

                handled = true;
            }
            break;

            // WM_UPDATEUISTATE is sent when the user presses ALT, expecting
            // the app to display accelerator keys.  We don't always hear the
            // keystroke - another message loop may handle it.  So report it
            // here.
            case WindowMessage.WM_UPDATEUISTATE:
            {
                RawUIStateInputReport report =
                    new RawUIStateInputReport(_source.Value,
                                              InputMode.Foreground,
                                              _msgTime,
                                              (RawUIStateActions)NativeMethods.SignedLOWORD((int)wParam),
                                              (RawUIStateTargets)NativeMethods.SignedHIWORD((int)wParam));

                _site.Value.ReportInput(report);

                handled = true;
            }
            break;
            }

            if (handled && EventTrace.IsEnabled(EventTrace.Keyword.KeywordInput | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info))
            {
                EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientInputMessage,
                                                    EventTrace.Keyword.KeywordInput | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info,
                                                    Dispatcher.GetHashCode(),
                                                    hwnd.ToInt64(),
                                                    message,
                                                    (int)wParam,
                                                    (int)lParam);
            }

            return(result);
        }
Пример #40
0
        internal HwndAppCommandInputProvider(HwndSource source)
        {
            _site = new SecurityCriticalDataClass <InputProviderSite>(InputManager.Current.RegisterInputProvider(this));

            _source = new SecurityCriticalDataClass <HwndSource>(source);
        }
 void win_SourceInitialized(object sender, EventArgs e)
 {
     System.IntPtr handle = (new WinInterop.WindowInteropHelper(this)).Handle;
     WinInterop.HwndSource.FromHwnd(handle).AddHook(new WinInterop.HwndSourceHook(WindowProc));
     hwndSource = PresentationSource.FromVisual((Visual)sender) as WinInterop.HwndSource;
 }
Пример #42
0
 public WpfWindowMessageHook(Window window)
 {
     _source        = (HwndSource)PresentationSource.FromDependencyObject(window);
     _interopHelper = new WindowInteropHelper(window);
 }
Пример #43
0
        private void BuildOrReparentWindow()
        {
            this.DemandIfUntrusted();
            if (this._isBuildingWindow || this._isDisposed)
            {
                return;
            }
            this._isBuildingWindow = true;
            IntPtr             intPtr             = IntPtr.Zero;
            PresentationSource presentationSource = PresentationSource.CriticalFromVisual(this, false);

            if (presentationSource != null)
            {
                HwndSource hwndSource = presentationSource as HwndSource;
                if (hwndSource != null)
                {
                    intPtr = hwndSource.CriticalHandle;
                }
            }
            else
            {
                PresentationSource presentationSource2 = PresentationSource.CriticalFromVisual(this, true);
                if (presentationSource2 != null && TraceHwndHost.IsEnabled)
                {
                    TraceHwndHost.Trace(TraceEventType.Warning, TraceHwndHost.HwndHostIn3D);
                }
            }
            try
            {
                if (intPtr != IntPtr.Zero)
                {
                    if (this._hwnd.Handle == IntPtr.Zero)
                    {
                        this.BuildWindow(new HandleRef(null, intPtr));
                        base.LayoutUpdated    += this._handlerLayoutUpdated;
                        base.IsEnabledChanged += this._handlerEnabledChanged;
                        base.IsVisibleChanged += this._handlerVisibleChanged;
                    }
                    else if (intPtr != UnsafeNativeMethods.GetParent(this._hwnd))
                    {
                        UnsafeNativeMethods.SetParent(this._hwnd, new HandleRef(null, intPtr));
                    }
                }
                else
                {
                    IntPtr value = (!FrameworkAppContextSwitches.DisableDevDiv1035544) ? this.Handle : this._hwnd.Handle;
                    if (value != IntPtr.Zero)
                    {
                        HwndWrapper dpiAwarenessCompatibleNotificationWindow = SystemResources.GetDpiAwarenessCompatibleNotificationWindow(this._hwnd);
                        if (dpiAwarenessCompatibleNotificationWindow != null)
                        {
                            UnsafeNativeMethods.SetParent(this._hwnd, new HandleRef(null, dpiAwarenessCompatibleNotificationWindow.Handle));
                            SystemResources.DelayHwndShutdown();
                        }
                        else
                        {
                            Trace.WriteLineIf(dpiAwarenessCompatibleNotificationWindow == null, string.Format("- Warning - Notification Window is null\n{0}", new StackTrace(true).ToString()));
                        }
                    }
                }
            }
            finally
            {
                this._isBuildingWindow = false;
            }
        }
Пример #44
0
 private void MainWindow_SourceInitialized(object sender, EventArgs e)
 {
     System.Windows.Interop.HwndSource source = System.Windows.Interop.HwndSource.FromHwnd(new System.Windows.Interop.WindowInteropHelper(this).Handle);
     source.AddHook(new System.Windows.Interop.HwndSourceHook(WndProc));
 }