Option Explicit
Private Const MONITORINFOF_PRIMARY = &H1
Private Const MONITOR_DEFAULTTONEAREST = &H2
Private Const MONITOR_DEFAULTTONULL = &H0
Private Const MONITOR_DEFAULTTOPRIMARY = &H1
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Type MONITORINFO
cbSize As Long
rcMonitor As RECT
rcWork As RECT
dwFlags As Long
End Type
Private Type POINT
x As Long
y As Long
End Type
Private Declare Function GetMonitorInfo Lib "user32.dll" Alias "GetMonitorInfoA" (ByVal hMonitor As Long, ByRef lpmi As MONITORINFO) As Long
Private Declare Function MonitorFromPoint Lib "user32.dll" (ByVal x As Long, ByVal y As Long, ByVal dwFlags As Long) As Long
Private Declare Function MonitorFromRect Lib "user32.dll" (ByRef lprc As RECT, ByVal dwFlags As Long) As Long
Private Declare Function MonitorFromWindow Lib "user32.dll" (ByVal hWnd As Long, ByVal dwFlags As Long) As Long
Private Declare Function EnumDisplayMonitors Lib "user32.dll" (ByVal hdc As Long, ByRef lprcClip As Any, ByVal lpfnEnum As Long, ByVal dwData As Long) As Long
Private Declare Function GetWindowRect Lib "user32" (ByVal hWnd As Long, lpRect As RECT) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Dim hWnd As Long
Private Function MonitorEnumProc(ByVal hMonitor As Long, ByVal hdcMonitor As Long, _
lprcMonitor As RECT, ByVal dwData As Long) As Long
Dim MI As MONITORINFO, R As RECT
Debug.Print "Moitor handle: " + CStr(hMonitor)
'initialize the MONITORINFO structure
MI.cbSize = Len(MI)
'Get the monitor information of the specified monitor
GetMonitorInfo hMonitor, MI
'write some information
Debug.Print "Monitor" & _
" Left " & MI.rcMonitor.Left & _
" Top " & MI.rcMonitor.Top & _
" Size " & MI.rcMonitor.Right - MI.rcMonitor.Left & "x" & MI.rcMonitor.Bottom - MI _
.rcMonitor.Top
Debug.Print "Primary monitor: " + CStr(CBool(MI.dwFlags = MONITORINFOF_PRIMARY))
'test
If MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST) = hMonitor Then
Debug.Print "hWnd is located on this monitor"
End If
'heck whether the point (0, 0) lies within the bounds of this monitor
If MonitorFromPoint(0, 0, MONITOR_DEFAULTTONEAREST) = hMonitor Then
Debug.Print "The point (0, 0) lies wihthin the range of this monitor..."
End If
'check whether Form1 is located on this monitor
GetWindowRect hWnd, R
If MonitorFromRect(R, MONITOR_DEFAULTTONEAREST) = hMonitor Then
Debug.Print "The rectangle of hWnd lies within this monitor"
End If
Debug.Print ""
'Continue enumeration
MonitorEnumProc = 1
End Function
Sub Main()
hWnd = FindWindow("XLMAIN", Application.Caption)
'start the enumeration
EnumDisplayMonitors ByVal 0&, ByVal 0&, AddressOf MonitorEnumProc, ByVal 0&
End Sub