Thanks for taking a look.
In my desktop application I'd like to move the mouse to the centre of the application window whenever a particular button is pressed. To this end I take the position, width and height of the main window, then set the mouse cursor position based on these values with User32.dll .
The mouse cursor is moved, however it is always significantly off center. Its position is influenced by the pos, width and height, but there seems to be some weird scaling issue between measuring the desired position and setting. Based on this question and its duplicate this is what I am using:
static public double GetWindowLeft(Window window)
{
if (window.WindowState == WindowState.Maximized)
{
var leftField = typeof(Window).GetField("_actualLeft", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
return (double)leftField.GetValue(window);
}
else
return window.Left;
}
static public double GetWindowTop(Window window)
{
if (window.WindowState == WindowState.Maximized)
{
var leftField = typeof(Window).GetField("_actualTop", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
return (double)leftField.GetValue(window);
}
else
return window.Top;
}
static public void SetPosition(int a, int b)
{
SetCursorPos(a, b);
}
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int X, int Y);
}
and in a MainWindow method:
private void CenterMouse(object sender, RoutedEventArgs e)
{
double top = UCMethods.GetWindowTop(this);
double left = UCMethods.GetWindowLeft(this);
SetPosition((int)(left+left+ActualWidth) / 2, (int)(top + top + ActualHeight) / 2);
}
Edit: This seems to run fine on my friend's computer, but has the offset on mine. The further I am from the top left corner of the screen (0,0), the more the mouse cursor lags behind in that direction (mouse cursor is offset in the top left direction). How could this problem be device specific?