Detecting which screen an app is running on in a multi-monitor setup can be a little tricky. Luckily there are a few handy utility functions available for you in the .NET framework under System.Windows.Forms.Screen.

However for applications that support fullscreen modes detecting the screen require a little extra trick as to achieve fullscreen the window bounds are made to actually extend the screen bounds by a little.

Differences between windowed and fullscreen modes

The code below handles this correctly:

public Screen DetectScreen ( IntPtr windowHandle ) { // Figure out which screen the window is located on (in a multi screen setup) var appWindowBounds = GetWindowBounds ( windowHandle ); foreach ( var screen in Screen . AllScreens ) { // If the app is not fullscreen then the screen.bounds will contain the window // if the app is fullscreen then IT will actually contain the screen bounds if ( screen . Bounds . Contains ( appWindowBounds ) || appWindowBounds . Contains ( screen . Bounds )) { return screen ; } } // By default use the primary screen return Screen . PrimaryScreen ; }

For completeness below is the implementation for the GetWindowBounds function.

[DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetWindowRect ( IntPtr hwnd , out RECT lpRect ); [StructLayout(LayoutKind.Sequential)] internal struct RECT { public int Left ; // x position of upper-left corner public int Top ; // y position of upper-left corner public int Right ; // x position of lower-right corner public int Bottom ; // y position of lower-right corner } private Rectangle GetWindowBounds ( IntPtr windowHandle ) { Win32 . RECT rct ; if (! Win32 . GetWindowRect ( windowHandle , out rct )) { return Rectangle . Empty ; } return rct . ToRectangle (); }

Please enable JavaScript to view the comments powered by Disqus.