How do I use CaptureMouse or Mouse.Capture in my C# WPF application?


I want to be able to access the coordinates of the mouse whether or not the cursor is over the window of my application.

When I use Mouse.Capture(IInputElement) or UIElement.CaptureMouse(), both fail to capture the mouse and return false.

What might be my problem?

The cs file for my window is as follows:

using System.Windows;
using System.Windows.Input;

namespace ScreenLooker
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
        public Window1()

            bool bSuccess = Mouse.Capture(this);
            bSuccess = this.CaptureMouse();

        protected override void OnMouseMove(MouseEventArgs e)
            tbCoordX.Text = e.GetPosition(this).X.ToString();
            tbCoordY.Text = e.GetPosition(this).Y.ToString();
            //System.Drawing.Point oPoint = System.Windows.Forms.Cursor.Position;
            //tbCoordX.Text = oPoint.X.ToString();
            //tbCoordY.Text = oPoint.Y.ToString();

1/13/2009 12:58:00 AM

Accepted Answer

The control passed to Mouse.Capture() needs to be Visible and Enabled.

Try putting the Mouse.Capture in the Loaded event handler, e.g.


<Window ... .. .. Title="My Window" loaded="Window_Loaded">

In Code:

private void Window_Loaded(object sender, RoutedEventArgs e)
  var b = Mouse.Capture(this);

I've not captured the whole window before, so not sure about how it will work. The typical usage of it is.

  1. MouseDown:- call Mouse.Capture() on child control
  2. MouseMove:- Process X and Y coords of mouse
  3. MouseUp:- call Mouse.Capture(null) to clear mouse event capture.
1/13/2009 10:57:22 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow