Find which display a window is in

I’ve been searching the documentation and got into an endless loop. My problem:
I have an app (several actually) which reset the window position to the last moved position when they are re-launched. It uses the Moved event and sets the left and top position during window open events. It works fine with one display.

But with multiple displays I can’t find the formula. I can set the screen (using, for example, me.top = screen( n ).previousTop). But I can’t figure out how to determine the screen number of the window after a move, so this technique always put the window on the main screen (which I don’t want).

How to find which screen a window is on ?

Thanks,
Richard

Multiple screens are generally handled as “viewports” of one whole huge area. A Window on the second screen might have coordinates of -2400, 100. You can in most cases just store the coordinates and not worry about which screen it is on.

It is when you’re restoring that you want to check that the screen still exists. Loop through the Screens and check whether the Window bounds are within the Screen bounds.

DisplayCount will help you loop.

Using Window.Bounds and Rects can save you the math of “is it on this screen” because Rects have Rect.Contains. You will need to build your own Rects for the screen bounds, but the Window bounds are already a Rect.

3 Likes

A window can spread over more than one display. You need to choose a point within the window and check which display that is sitting on. Some choose the top left, but that can be moved outside of all displays. I’ve chosen the centre of the window. The following code will then tell you which display that is on:

Var iDisplay As Integer = WhichScreen( Self.Left + ( Self.Width / 2 ), Self.Top + ( Self.Height / 2 ) )
// iDisplay you which display you are on.
// DesktopDisplay.DisplayAt( iDisplay ) gives properties of that display.

Var oDisplay As DesktopDisplay
For iDisplay As Integer = 0 To DesktopDisplay.LastDisplayIndex
  oDisplay = DesktopDisplay.DisplayAt( iDisplay )
  If x >= oDisplay.AvailableLeft And x <= oDisplay.AvailableWidth + oDisplay.AvailableLeft And _
    y >= oDisplay.AvailableTop And y <= oDisplay.AvailableHeight + oDisplay.AvailableTop Then
    Return iDisplay
  End If
Next
2 Likes

Thanks both of you. I can make something from these inputs. But that’s a job for tomorrow as it’s now getting late here.