查找存在鼠标指针的监视器/屏幕

Mus*_*lah 3 c# wpf mouse

我将从头开始,我正在开发一个跨越多个监视器的应用程序,每个监视器将包含一个WPF窗口,并且这些窗口使用单个viewmodel类进行控制.现在假设我在200,300(x,y)的所有窗口上都有一个按钮,我希望这个按钮应该负责同一窗口上的工具,而所有其他人都负责应用程序.当我尝试获取当前鼠标位置或最后点击位置时,我获得相对于当前监视器的位置,即在这种情况下为200,300,而不管我在哪个屏幕上.

下面是我尝试获取鼠标位置的代码

  1. [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool GetCursorPos(ref Win32Point pt);
    
    [StructLayout(LayoutKind.Sequential)]
    internal struct Win32Point
    {
        public Int32 X;
        public Int32 Y;
    };
    
    public static Point GetMousePosition()
    {
        Win32Point w32Mouse = new Win32Point();
        GetCursorPos(ref w32Mouse);
        return new Point(w32Mouse.X, w32Mouse.Y);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. Point point = Control.MousePosition;

  3. Mouse.GetPosition(null);

以下是应该返回屏幕号的代码.

private int ConvertMousePointToScreenIndex(System.Windows.Point mousePoint)
    {
        //first get all the screens 
        System.Drawing.Rectangle ret;

        for (int i = 1; i <= System.Windows.Forms.Screen.AllScreens.Count(); i++)
        {
            ret = System.Windows.Forms.Screen.AllScreens[i - 1].Bounds;
            if (ret.Contains(new System.Drawing.Point((int)mousePoint.X, (int)mousePoint.Y)))
                return i - 1;
        }
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我总是将屏幕设为0 :(请帮助我获得适当的价值

小智 14

你能用Screen静态类吗?

例如,类似于:

Screen s = Screen.FromPoint(Cursor.Position);
Run Code Online (Sandbox Code Playgroud)

或者使用以下方法从特定表单获取当前屏幕:

Screen s = Screen.FromControl(this);
Run Code Online (Sandbox Code Playgroud)

随着this被你的窗体控件.

http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx

  • 很好的答案,谢谢你,但你可以更加简化它.Cursor.Position已经是一个Point.所以`Screen.FromPoint(new Point(Cursor.Position.X,Cursor.Position.Y))`可以只是`Screen.FromPoint(Cursor.Position)` (2认同)

Mus*_*lah 5

感谢 KnottytOmo,它现在起作用了,当时可能还有其他问题。我将代码更改为

 private int ConvertMousePointToScreenIndex(Point mousePoint)
    {
        //first get all the screens 
        System.Drawing.Rectangle ret;

        for (int i = 1; i <= Screen.AllScreens.Count(); i++)
        {
            ret = Screen.AllScreens[i - 1].Bounds;
            if (ret.Contains(mousePoint))
                return i - 1;
        }
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

并将其称为 ConvertMousePointToScreenIndex(System.Windows.Forms.Cursor.Position);