2

I need a simple win api inside c# / vb.net, to read a text out of a message box. I have a function to read a message box title, but i have no idea how to get the content text. The messagebox title function is:

' Function to retrieve the popup window associated with the form, as well as to
' find the child windows of the popup...
Private Declare Auto Function GetWindow Lib "user32.dll" ( _
    ByVal hWnd As IntPtr, ByVal uCmd As Long) As IntPtr

' Sendmessage overload that is used to send messages to the button on the
' dialog window...
Private Declare Auto Function SendMessage Lib "user32.dll" Alias "SendMessage" _
    (ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, _
     ByRef lParam As IntPtr) As IntPtr

' Sendmessage overloads used to retrieve the window text...
Private Declare Auto Function SendMessageA Lib "user32.dll" _
    Alias "SendMessageA" (ByVal hWnd As IntPtr, ByVal Msg As Integer, _
        ByVal wParam As IntPtr, ByRef lParam As IntPtr) As IntPtr

...

' This function returns the text of the window, used so that we can confirm that
' we have the right dialog window...
Private Function GetWindowText(ByVal WindowHandle As IntPtr) As String
    Dim ptrRet As IntPtr
    Dim ptrLength As IntPtr

    ' Get length for buffer...
    ptrLength = SendMessageA( _
        WindowHandle, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero)

    ' Create buffer for return value...
    Dim sb As New System.Text.StringBuilder(ptrLength.ToInt32 + 1)

    ' Get window text...
    ptrRet = SendMessageString( _
        WindowHandle, WM_GETTEXT, ptrLength.ToInt32 + 1, sb)

    ' Get return value...
    Return sb.ToString
End If
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
ilans
  • 2,537
  • 1
  • 28
  • 29

1 Answers1

3

You are probably using the wrong window handle. The text is displayed by a client window inside the message box. You can get its handle by pinvoke GetDlgItem(), passing ID 65535. Use Spy++ to get insight into the parts that make up the message box window.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Thanks Hansen. What do I do with this handle? how do I get the text? – ilans Apr 29 '12 at 08:32
  • Pinvoke GetWindowText(). You need to watch out for bad VB6 declarations, like your GetDlgItemText(). Find .NET ones at www.pinvoke.net – Hans Passant Apr 29 '12 at 09:19
  • Hi Hansen. I appreciate the help, but I give up... i tried to use both "SendMessage" and "GetDlgItemText" that get a stringbuilder, it also didn't work. I have no idea how to use those functions. I didn't see any examples on the internet. The only data I believe to have is (probably) the id of the window of the message box. I'm not sure about that either anymore. – ilans Apr 29 '12 at 10:46