44using Windows . Foundation ;
55using System . Collections . Generic ;
66using Windows . Win32 ;
7+ using System ;
78
89namespace WinUIEx
910{
@@ -18,27 +19,36 @@ public class MonitorInfo
1819 /// <returns>A list of display monitors</returns>
1920 public unsafe static IList < MonitorInfo > GetDisplayMonitors ( )
2021 {
22+
2123 int monitorCount = PInvoke . GetSystemMetrics ( Windows . Win32 . UI . WindowsAndMessaging . SYSTEM_METRICS_INDEX . SM_CMONITORS ) ;
2224 List < MonitorInfo > list = new List < MonitorInfo > ( monitorCount ) ;
23- MONITORENUMPROC callback = new MONITORENUMPROC ( ( HMONITOR monitor , HDC deviceContext , RECT * rect , LPARAM data ) =>
24- {
25- list . Add ( new MonitorInfo ( monitor , rect ) ) ;
26- return true ;
27- } ) ;
28- LPARAM data = new LPARAM ( ) ;
29- bool ok = PInvoke . EnumDisplayMonitors ( new HDC ( 0 ) , ( RECT ? ) null , callback , data ) ;
25+ var cbhandle = GCHandle . Alloc ( list ) ;
26+ var ptr = GCHandle . ToIntPtr ( cbhandle ) ;
27+
28+ LPARAM data = new LPARAM ( ptr ) ;
29+ bool ok = PInvoke . EnumDisplayMonitors ( new HDC ( 0 ) , ( RECT ? ) null , & MonitorEnumProc , data ) ;
30+ cbhandle . Free ( ) ;
3031 if ( ! ok )
3132 Marshal . ThrowExceptionForHR ( Marshal . GetLastWin32Error ( ) ) ;
3233 return list ;
3334 }
3435
36+ [ UnmanagedCallersOnly ( CallConvs = new Type [ ] { typeof ( System . Runtime . CompilerServices . CallConvStdcall ) } ) ]
37+ private unsafe static BOOL MonitorEnumProc ( HMONITOR hMonitor , HDC hdcMonitor , RECT * lprcMonitor , LPARAM dwData )
38+ {
39+ var handle = GCHandle . FromIntPtr ( dwData . Value ) ;
40+ if ( ! lprcMonitor ->IsEmpty && handle . IsAllocated && handle . Target is List < MonitorInfo > list )
41+ list . Add ( new MonitorInfo ( hMonitor , * lprcMonitor ) ) ;
42+ return new BOOL ( 1 ) ;
43+ }
44+
3545 private readonly HMONITOR _monitor ;
3646
37- internal unsafe MonitorInfo ( HMONITOR monitor , RECT * rect )
47+ internal unsafe MonitorInfo ( HMONITOR monitor , RECT rect )
3848 {
3949 RectMonitor =
40- new Rect ( new Point ( rect -> left , rect -> top ) ,
41- new Point ( rect -> right , rect -> bottom ) ) ;
50+ new Rect ( new Point ( rect . left , rect . top ) ,
51+ new Point ( rect . right , rect . bottom ) ) ;
4252 _monitor = monitor ;
4353 var info = new MONITORINFOEXW ( ) { monitorInfo = new MONITORINFO ( ) { cbSize = ( uint ) sizeof ( MONITORINFOEXW ) } } ;
4454 GetMonitorInfo ( monitor , ref info ) ;
0 commit comments