Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
338 views
Welcome To Ask or Share your Answers For Others

1 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.

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...