There is an application that runs pretty much 24/7 on this computer. It is run inside a command prompt Window. I would like to be able to capture all of the text currently displayed in the window.
The application is already running (and for unrelated reasons, can't be launched from within VB), so I can't just redirect the output of the process to save the text.
My current method for capturing the text is with the following code:
SendKeys.SendWait("^(a)")
SendKeys.SendWait("^(a)")
SendKeys.SendWait("{enter}")
Dim CmdText As String = Clipboard.GetText
Clipboard.Clear()
The above code sends a select all command to the window (it sends it twice, otherwise the entire windows text isn't captured). It then hits the enter key to load it into the clipboard. I then save the clipboard contents to a variable. It works well, but the major problem is that it requires the window to be in focus.
Is there anyway to capture the text from the CMD window if it is currently out of focus?
Edit: I think I'm getting close to finding a workaround using sendmessage/postmessage. Here is the current code:
Private Declare Function PostMessage Lib "user32.dll" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
Private Const WM_CHAR As Long = &H102
Private Const VK_CONTROL = &H11
Private Const VK_RETURN = &HD
Public Function GetWindowHandle(ByVal processName As String) As IntPtr
processName = System.IO.Path.GetFileNameWithoutExtension(processName)
Dim p() = Process.GetProcessesByName(processName)
Return If(p.Length > 0, p(0).MainWindowHandle, IntPtr.Zero)
End Function
Private Sub GetText()
Dim h As Long = GetWindowHandle("programname.exe")
SendMessage(h, WM_CHAR, 1, 0) 'suppose to simulate Ctrl + A
SendMessage(h, WM_CHAR, 1, 0) 'suppose to simulate Ctrl + A
PostMessage(h, WM_KEYDOWN, VK_RETURN, 0) 'sends enter key to load text into clipboard
End Sub
The problem is that instead of sending Ctrl + A to the command window, it just sends the text ^A. Any ideas?