How to open an URL in an existing browser window using C++ on Windows

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To open a URL in an existing browser window using C++ on Windows, you can utilize the ShellExecute function from the Windows API. Here's an example:

cpp
#include <windows.h>

int main() {
const char* url = "https://www.example.com";

HWND browserWindow = FindWindow("Chrome_WidgetWin_1", NULL);
if (browserWindow != NULL) {
ShellExecute(browserWindow, "open", url, NULL, NULL, SW_SHOW);
}

return 0;
}

In this example, we use the FindWindow function to retrieve the handle (HWND) of the existing browser window. The first argument to FindWindow is the class name of the browser window, which may vary depending on the browser you are using (e.g., "Chrome_WidgetWin_1" for Google Chrome). The second argument is the window title, which we set to NULL to search for any window with the specified class name.

If the FindWindow function successfully finds the browser window, we pass the window handle (HWND) to the ShellExecute function. The second argument is set to "open" to indicate that we want to open the specified URL. The third argument is the URL itself. The remaining arguments can be set to NULL or omitted for default behavior.

Finally, we use the SW_SHOW constant to specify the display mode of the browser window when opening the URL.

Note that this example assumes you have a running instance of the browser with a visible window before executing the program. Additionally, the class name used in FindWindow may differ depending on the browser you are using, so you may need to adjust it accordingly.

By using the ShellExecute function with the appropriate browser window handle, you can open a URL in an existing browser window using C++ on Windows.