Saturday, July 25, 2020

How to get the contents of MessageBox of other process by reverse lookup from Caption

Private Declare PtrSafe Function FindWindowW Lib "user32" (ByVal lpClassName As LongPtr, ByVal lpWindowName As LongPtr) As LongPtr
Private Declare PtrSafe Function GetWindowTextLengthW Lib "user32" (ByVal hwnd As LongPtr) As Long
Private Declare PtrSafe Function GetDlgItem Lib "user32" (ByVal hDlg As LongPtr, ByVal nIDDlgItem As Long) As LongPtr
Private Declare PtrSafe Function FindWindowExW Lib "user32" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As LongPtr, ByVal lpsz2 As LongPtr) As LongPtr
Private Declare PtrSafe Function GetWindowTextW Lib "user32" (ByVal hwnd As LongPtr, ByVal lpString As LongPtr, ByVal cch As Long) As Long

Private Function GetPrompt(ByVal Caption As String) As String
    Dim hWndDialog As LongPtr
    Dim hWndMessage As LongPtr
    Dim nLength As Long
    Dim sText As String
    
    hWndDialog = FindWindowW(0, StrPtr(Caption))
    If hWndDialog Then
        hWndMessage = GetDlgItem(hWndDialog, &HFFFF&)
        If hWndMessage Then
            nLength = GetWindowTextLengthW(hWndMessage) + 1
            sText = String(nLength, vbNullChar)
            nLength = GetWindowTextW(hWndMessage, StrPtr(sText), nLength)
            GetPrompt = Mid(sText, 1, nLength)
        End If
    End If
End Function
Sub ma()
'Make a vbscript file like this.
'   MsgBox "Something wrong",vbOKOnly, "Application Error"
'And run that vbscript file before running this excel macro.
'This macro retrives "Something wrong" by specifing the caption:"Application Error"
    Debug.Print GetPrompt("Application Error")
End Sub

No comments: