【问题标题】:c# Get Active Window Text (causes vshost32.exe has stopped working)c#获取活动窗口文本(导致vshost32.exe停止工作)
【发布时间】:2016-09-29 16:23:51
【问题描述】:

我基本上是在运行一个获取活动窗口文本的 Windows 窗体,例如 Google Chrome - 一些文本:

我的方法在这里:

public static String GetActiveWindowText()
{  
        var handle = GetForegroundWindow();
        var sb = new StringBuilder();
        GetWindowText(handle, sb, 1000);
        return sb.Length == 0 ? "Unhand Window" : sb.ToString();
}

对于GetForegroundWindow():

[DllImport("user32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetForegroundWindow()

注意:当我尝试使用记事本或类似的程序(如记事本或 blocknote)时,它运行良好,但当我在 Google Chrome 上尝试时,它会导致程序崩溃 vshost32.exe 已停止工作。

【问题讨论】:

  • 您应该将您的解决方案添加为答案,然后将其标记为已接受(在时间限制之后)。
  • @Bradley Uffner 成功了! ,谢谢!

标签: c# winforms


【解决方案1】:

已解决

我必须先得到文本的长度:

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 是:

[DllImport("user32.dll", SetLastError= true, CharSet= CharSet.Auto)]
public static extern Int32 GetWindowTextLength(IntPtr hWnd);

【讨论】:

    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 2017-01-06
    相关资源
    最近更新 更多