tags:

views:

5427

answers:

1

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()
        {
            InitializeComponent();

            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();

            base.OnMouseMove(e);
        }
    }
}
+2  A: 

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

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

In XAML:

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

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.
Rhys
Thanks. I had checked whether or not the window was enabled, but not whether or not it was active.Even after capturing the mouse, MouseMove is still only being raised when the mouse is within the window. Perhaps Capture is not what I want after all?
Paul Williams