2014-10-16 53 views
1

我将从头开始,我将在跨越多个监视器的应用程序上工作,每个监视器将包含一个WPF窗口,并且这些窗口使用单个viewmodel类进行控制。现在可以说我在200,300(x,y)的所有窗口上都有一个按钮,我希望这个按钮应该在同一个窗口中负责工具,而所有其余部分都负责应用程序。 当我尝试获取当前鼠标位置或最后一次点击位置时,我获取相对于当前监视器的位置,即在本例中为200,300,而不管在我处于何种屏幕上。查找监视器/屏幕上存在鼠标指针

以下SRE我尝试了让下面的鼠标位置

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

我总是屏幕0 :( 请帮我在得到合适的值

+0

'Cursor.Position'将返回非相对位置 - (X,Y)... +(X,Y) – 2014-10-16 11:22:23

回答

2

感谢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; 
    } 

,并呼吁它作为ConvertMousePointToScreenIndex(System.Windows.Forms.Cursor.Position);

+0

很高兴能帮到你:) – KnottytOmo 2014-10-17 08:26:56

10

你可以使用Screen静态类

例如,像:

Screen s = Screen.FromPoint(new Point(Cursor.Position.X, Cursor.Position.Y)); 

或者从以下特定形式获取当前屏幕:

Screen s = Screen.FromControl(this); 

this是您的窗体控件。

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

+0

点我得到的是相对于显示器而不是通用的,即使在第二台显示器上,我得到的点是70,150。这会给我一个结果作为主监视器,即屏幕[0] – 2014-10-16 11:21:01

+0

@MustahsanAbdullah,你可以使用'Cursor.Position'。 – KnottytOmo 2014-10-16 11:25:43

+0

我已经尝试过了,并且它没有帮助:( – 2014-10-16 12:04:39