Hi,

I have a button btnRegEx that when pressed shows a ContextMenuStrip, similar to the '>' button in the Find/Replace dialog in Visual Studio when you are using Regular Expressions.

I have a ContextMenuStrip cms which I show using its Show(x,y) method.

At first I was simply setting x and y (the location of the ContextMenuStrip) to some point next to the button, but I noticed that when the button is close to the edge of the screen it goes off screen. I wanted to prevent that so I built some logic into the x-y calculation.
When the ContextMenuStrip width is larger than the 'remaining space left' I simply show it more to the left. Same for its Height of course.

I am using the Screen.GetWorkingArea(point) method to determine the 'remaining space left'. As I understand it, it returns the working area closest to the point you specify (to which I pass the button's location).

As long as I stay on my first monitor, it is all working perfectly fine. The problem occurs when I move the form to my second monitor. The contextmenustrip is still showing on the first monitor for some reason...

Here is the code I am using:
vb.net Code:
  1. Private Sub btnRegEx_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRegEx.Click
  2.         Dim p As Point = PointToScreen(New Point(btnRegEx.Left, btnRegEx.Top))
  3.         Dim x, y As Integer
  4.  
  5.         Dim openWidth As Integer = Screen.GetWorkingArea(p).Width - p.X
  6.         If cms.Width > openWidth Then
  7.             x = Screen.GetWorkingArea(p).Width - cms.Width
  8.         Else
  9.             x = p.X + btnRegEx.Width + 2
  10.         End If
  11.         Dim openHeight As Integer = Screen.GetWorkingArea(p).Height - p.Y
  12.         If cms.Height > openHeight Then
  13.             y = Screen.GetWorkingArea(p).Height - cms.Height
  14.         Else
  15.             y = p.Y + btnRegEx.Height + 2
  16.         End If
  17.  
  18.         cms.Show(x, y)
  19.     End Sub

I have noticed that when I click the button when the form is on the second monitor, the buttons location (p) is calculated with the first monitor's top-left corner as (0,0), even though it is on the second monitor.
This way, the GetWorkingArea function returns something like 1280, while the buttons x-location is something like 1700...

So, how do I get the buttons coordinate relative to the actual screen it is on, rather than the entire dual monitor screens as a whole?