Question

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!

Was it helpful?

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); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top