2

Having worked out how to obtain the mouse click position anywhere along the monitor boundaries using low level hooks I receive an X Y coordinate that will contain a value typically between x: -1680 to +1920 and y: 0 to 1200 in my pcs case. Easy enough!

Now the problem is that I now want to calculate the mouse position relative to a given window that I have so I use GetForegroundWindow() and GetWindowRect(HandleRef hWnd, out RECT lpRect) to obtain my active window coordinates.

Where I am stuck is I require the current active desktop (By active I mean which monitor the click occurred on) to calculate the coordinates of my mouse click relative to a window.

Unfortunately I have not been able to find an API call like GetActiveMonitor() or similar so hopefully someone can point me in the right direction?

Maxim Gershkovich
  • 45,951
  • 44
  • 147
  • 243

2 Answers2

1

My guess is that you can know where your mouse is by using an if:

if(mousePosition.X > -1680 && mousePosition.X < 0)
      //We are in monitor 1;
else
      //Monitor 2;
Thanatos
  • 1,176
  • 8
  • 18
  • While you are right in that this would give me a confirmation of which monitor the click occurred in (this is a method I considered myself) it does not reconcile this information with the active monitor resolution. – Maxim Gershkovich Aug 25 '12 at 14:46
  • But can't you check which monitor is the active one by looking in the Settings Tab in the Display Proprieties from the Desktop? Or you want to use the program on another computer, rather than yours? – Thanatos Aug 25 '12 at 14:57
1
[DllImport("user32.dll", SetLastError = true)]
 [return: MarshalAs(UnmanagedType.Bool)]
 static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
 [StructLayout(LayoutKind.Sequential)]
 private struct RECT
 {
     public int Left;
     public int Top;
     public int Right;
     public int Bottom;
  }
Call it as:

  RECT rct = new RECT();
  GetWindowRect(hWnd, ref rct);

after get your mouse position like this

int mouserelativepositionX = mousePosition.X - rct.Left;
int mouserelativepositionY = mousePosition.Y - rct.Top;
Hassan Boutougha
  • 3,871
  • 1
  • 17
  • 17