c# - GetWindowText() 函数并非始终正确执行

标签 c# visual-studio-2012 .net-4.5 interopservices vshost32

我正在编写一个小应用程序,我希望从 Chrome 浏览器中获取 URL。

为了首先检查 Chrome 浏览器是否打开,我使用以下代码:

 IntPtr WindowTitleTextPtr = GetForegroundWindow();

 StringBuilder WindowTitleText = new StringBuilder();

 GetWindowText(WindowTitleTextPtr, WindowTitleText, 256); // Problem

 ...

我正在使用 GetWindowText() 函数来获取 Windows 标题文本,但我在那里遇到了问题。

如果 Chrome 窗口没有 URL,只是一个新标签,那么我没有问题,WindowTitleText.ToString() 等于 New Tab - Google Chrome

但是,如果我打开一个网页,在这种情况下,URL 会填充一些 URL,然后在 GetWindowText() 行,我得到: vs32host.exe 已停止工作 消息窗口要求我 enter image description here

这是怎么回事?

帮助!

最佳答案

您应该在 StringBuilder 实例中分配内存:

  StringBuilder WindowTitleText = new StringBuilder();

  int size = 256;
  WindowTitleText.Length = size; // <- Memory allocation

  // Read text into allocated memory
  GetWindowText(WindowTitleTextPtr, WindowTitleText, WindowTitleText.Length); 

关于c# - GetWindowText() 函数并非始终正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17377453/

相关文章:

c# - "using" block 对SqlCommand初始化的好处

c# - Entity Framework 实体不在 DataSpace.OSpace (_workspace.GetItemCollection(DataSpace.OSpace)) 但在 DataSpace.CSpace

c# - 可嵌入文件打开对话框

c# - 为什么 IEnumerable.ToList 会产生新的对象

c# - 如何通过Word文档修改 "walk"的内容?

visual-studio-2012 - 通过 Visual Studio 2015 使用 Visual Studio 2012 工具进行编译

mysql - 使用 Between 无法正常工作选择带日期的查询

c# - 用于错误描述的 visual studio 键盘快捷键

c# - 规范中是否实现了自动属性?

c# - 在 .NET 4.5 beta 中获取 System.Net.Mail.MailMessage 作为 MemoryStream