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:
Private Sub btnRegEx_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRegEx.Click Dim p As Point = PointToScreen(New Point(btnRegEx.Left, btnRegEx.Top)) Dim x, y As Integer Dim openWidth As Integer = Screen.GetWorkingArea(p).Width - p.X If cms.Width > openWidth Then x = Screen.GetWorkingArea(p).Width - cms.Width Else x = p.X + btnRegEx.Width + 2 End If Dim openHeight As Integer = Screen.GetWorkingArea(p).Height - p.Y If cms.Height > openHeight Then y = Screen.GetWorkingArea(p).Height - cms.Height Else y = p.Y + btnRegEx.Height + 2 End If cms.Show(x, y) 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?




Reply With Quote