Search code examples
c#visual-studio-2012.net-4.5interopservicesvshost32

GetWindowText() function is not executing correctly at all times


I'm writing a small application where I wish to get the URL from the Chrome browse.

In order to first check if the Chrome browser is open or not I use the following code:

 IntPtr WindowTitleTextPtr = GetForegroundWindow();

 StringBuilder WindowTitleText = new StringBuilder();

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

 ...

I'm using GetWindowText() function to get the Windows title text, but I'm facing a problem there.

If the Chrome window has NO URL and is simply a New Tab then I have no issues, WindowTitleText.ToString() is equal to New Tab - Google Chrome.

However if I open a webpage, in which case the URL is filled with some URL then at the line GetWindowText() I get: vs32host.exe has stopped working message window asking for me to enter image description here

What's going on?

Help!


Solution

  • You should allocate memory within the StringBuilder instance:

      StringBuilder WindowTitleText = new StringBuilder();
    
      int size = 256;
      WindowTitleText.Length = size; // <- Memory allocation
    
      // Read text into allocated memory
      GetWindowText(WindowTitleTextPtr, WindowTitleText, WindowTitleText.Length);