VBA Code Library

Move your window to the left screen and maximize it with VBA. Placing your window in a consistent position is a must before using mouse control macros. This is especially important if you’re using VBA to control your mouse and you have dual monitors.

This example maximizes a blank notepad window, but you can change the window you want to move by modifying the string in the AppActivate function.

A word of warning: The SendKeys method of VBA is quite unreliable, so use it with caution.


Maximize Window in Left Monitor

#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
    Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
#Else
    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems
    Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
#End If
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Sub MaximizeWindow()
'DESCRIPTION: Move window to the left screen and maximize it to full screen
'DEVELOPER: Ryan Wells (wellsr.com)

'NOTE:  You can change AppActivate string to the name of your window if there's a particular window you want to maximize

On Error GoTo 101:
AppActivate "Untitled - Notepad"

SendKeys "% ", True 'Alt space
    Sleep 250
SendKeys "r", True
    Sleep 250
SendKeys "% ", True 'Alt space
    Sleep 250
SendKeys "m", True
    Sleep 250
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
        Sleep 250
    SetCursorPos 0, 0 'x and y position
        Sleep 250
mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    Sleep 250
SendKeys "% ", True 'Alt space
    Sleep 250
SendKeys "x", True
Exit Sub
101:
MsgBox "Window not found", , "Window not found"
End Sub

I hope you found this VBA Code Library example helpful. Submit a comment below if you like this macro or have more questions. As always, subscribe to my email list, share this article on social media and follow me on Google+ and Twitter for more great VBA content!


wellsrPRO

Coming Fall 2017

Auto-Import Macros Directly from wellsr.com

Absolutely FREE when you join the waitlist


About Ryan Wells


Ryan Wells

Ryan Wells is a Nuclear Engineer and professional VBA Developer. He is the lead developer of several VBA applications, including PDF VBA - a leading Excel Add-in for exporting Excel Objects, like charts and tables, to PDFs. Discover more of his popular Excel Add-ins, including Mouse To Macro and CF Shapes, at his dedicated Excel Add-ins page.