excelvbasendkeys

What is Application.Sendkeys for "Windows" key in VBA?


There is no documentation of "windows" key :https://learn.microsoft.com/en-us/office/vba/api/excel.application.sendkeys

I wanted a combination of "Windows+UP" key to Maximize Active window. So, I tried "Ctrl+Esc" for windows key + {UP} : Application.SendKeys ("^({ESC}{UP})") but it didn't work.

Is there a way to send windows key using API, dll etc without using external programs like AutoIt.


Solution

  • Is there a way to send windows key using API, dll etc without using external programs like AutoIt

    Yes, you can use FindWindow and ShowWindow API to maximize a window. This is more reliable than using Sendkeys.

    Here is an example

    Option Explicit
    
    Private Declare PtrSafe Function ShowWindow Lib "user32" _
    (ByVal hwnd As LongPtr, ByVal nCmdSHow As Long) As Long
    
    Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" _
    (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
    
    Private Const SW_SHOWMAXIMIZED = 3
    
    Sub MaximizeAWindow()
        Dim hwnd As Long
        Dim Caption As String
        
        Caption = "THIS IS THE CAPTION OF THE WINDOW"
        
        hwnd = FindWindow(vbNullString, Caption)
        
        If hwnd <> 0 Then
            ShowWindow hwnd, SW_SHOWMAXIMIZED
        Else
            MsgBox "Unable to find the window. Is the caption correct?"
        End If
    End Sub
    

    You may be also interested in GetForegroundWindow and the GetWindowText API to get the caption of the current active window?