I'm basically running a Windows Form that get the text of an active window, for example Google Chrome - some text :
My method here:
public static String GetActiveWindowText()
{
var handle = GetForegroundWindow();
var sb = new StringBuilder();
GetWindowText(handle, sb, 1000);
return sb.Length == 0 ? "Unhand Window" : sb.ToString();
}
for GetForegroundWindow():
[DllImport("user32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetForegroundWindow()
Note : When I try on a Notepad or similar program like notepad or blocknote it works perfectly but when I try it on Google Chrome it causes the program to crash vshost32.exe has stopped working.
SOLVED :
I had to get the Length of the Text First :
public static String GetActiveWindowText()
{
var handle = GetForegroundWindow();
int length = GetWindowTextLength(handle); // Length First
var sb = new StringBuilder(length + 1);
GetWindowText(handle, sb, sb.Capacity);
return sb.Length == 0 ? "Unhand Window" : sb.ToString();
}
GetWindowTextLength is :
[DllImport("user32.dll", SetLastError= true, CharSet= CharSet.Auto)]
public static extern Int32 GetWindowTextLength(IntPtr hWnd);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.