2014-10-16 75 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