예제 #1
0
    public static Point GetAbsolutePosition(this Window w)
    {
        if (w.WindowState != WindowState.Maximized)
        {
            return(new Point(w.Left, w.Top));
        }

        Int32Rect r;
        bool      multimonSupported = OSInterop.GetSystemMetrics(OSInterop.SM_CMONITORS) != 0;

        if (!multimonSupported)
        {
            OSInterop.RECT rc = new OSInterop.RECT();
            OSInterop.SystemParametersInfo(48, 0, ref rc, 0);
            r = new Int32Rect(rc.left, rc.top, rc.width, rc.height);
        }
        else
        {
            WindowInteropHelper helper   = new WindowInteropHelper(w);
            IntPtr hmonitor              = OSInterop.MonitorFromWindow(new HandleRef(null, helper.EnsureHandle()), 2);
            OSInterop.MONITORINFOEX info = new OSInterop.MONITORINFOEX();
            OSInterop.GetMonitorInfo(new HandleRef(null, hmonitor), info);
            r = new Int32Rect(info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.width, info.rcMonitor.height);
        }
        return(new Point(r.X, r.Y));
    }
예제 #2
0
    /// <summary>
    /// Constrain mouse cursor to the area of the specified UI element.
    /// </summary>
    /// <param name="element">Target UI element.</param>
    /// <returns>True on success.</returns>
    public static bool ClipCursor(FrameworkElement element)
    {
        const double dpi96 = 96.0;

        var topLeft = element.PointToScreen(new Point(0, 0));

        PresentationSource source = PresentationSource.FromVisual(element);

        if (source?.CompositionTarget == null)
        {
            return(false);
        }

        double dpiX = dpi96 * source.CompositionTarget.TransformToDevice.M11;
        double dpiY = dpi96 * source.CompositionTarget.TransformToDevice.M22;

        var width  = (int)((element.ActualWidth + 1) * dpiX / dpi96);
        var height = (int)((element.ActualHeight + 1) * dpiY / dpi96);

        OSInterop.RECT rect = new OSInterop.RECT
        {
            left   = (int)topLeft.X,
            top    = (int)topLeft.Y,
            right  = (int)topLeft.X + width,
            bottom = (int)topLeft.Y + height
        };

        return(OSInterop.ClipCursor(ref rect));
    }