I'm using VB 2010 to automate an application running on an external Windows console (cmd.exe). Note that I want to continue using the external console normally but, from time to time, I want to capture the console text from the VB application. I have no problem to send text commands to the console from buttons on my VB application using, for example:
...
Dim As IntPtr = FindWindow destination ("ConsoleWindowClass", "consoleapp")
SendMessage (destination, WM_CHAR, VK_RETURN, "")
...
However, it seems impossible to get the text that appears in the console window. I tried using standard output redirection:
...
oStartInfo = New ProcessStartInfo ("consoleapp.exe")
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start ()
...
And then I read the output stream using:
....
Dim oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadLine ()
....
This way I can read the standard output from my VB application, but I can not use the console because the console does not show any text (since it has been redirected!). On the other hand, you can not change the standard output redirection once the console process is started.
I have also tried to use 'GetWindowText', but does not work with windows belonging to other applications.
Now I am using 'SendMessage' and 'WM_GETTEXT' as follows:
...
Dim windowhandle As IntPtr = FindWindow ("ConsoleWindowClass", "consoleapp")
Dim ChildHandle As IntPtr = FindWindowEx (windowhandle, IntPtr.Zero, Nothing, Nothing)
Dim RcvText As String
'Alloc memory for the buffer That recieves the text
Dim mybuffer As IntPtr = Marshal.AllocHGlobal (200)
'The WM_GETTEXT Send Message
SendMessage (ChildHandle, WM_GETTEXT, 200, mybuffer)
'Copy the characters from the unmanaged memory to a managed string
RcvText = Marshal.PtrToStringUni(mybuffer)
'Display the string
Debug.Print (RcvText)
...
But all I get are strange text strings, but nothing of the text content of the console.
Since the console window has no child windows, I tried to use SendMessage (Windowhandle...) instead of SendMessage (ChildHandle...), but the result is also weird strings ...
Is there a way to read the text of a Windows console using VB?
Thank you very much for your help.