Creating a Program to Open Google Chrome

I've been searching for a long time to find a way to make a cpp program that opens google chrome and goes to a specified url and nothing is working. This is the current code i'm using but its not working because no one really specifies the includes & dlls necessary for execution or if they do they compile with errors....err.. so frustrating... anyone have any thoughts?

This is the basic code i've been using. Apparently, ShellExecute is the preferred method to do it. Its not really turning out to be my favorite right now...

1
2
3
4
5
 
int main(){
	ShellExecute(NULL, "open", "http://www.microsoft.com", NULL, SW_SHOWDEFAULT);
	return 0;
}
It really depends on your target platform. ShellExecute is a windows function, I know that much at least.

One would assume that you would need to include <windows.h> and use winmain instead of main for starters.
You don't need to use winmain.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <windows.h>
#include <shellapi.h>

bool open_browser( const char* url, HWND parent = NULL )
  {
  // Try normally, with the default verb (which will typically be "open")
  HINSTANCE result = ShellExecuteA( parent, NULL, url, NULL, NULL, SW_SHOWNORMAL );

  // If that fails due to privileges, let's ask for more and try again
  if ((int)result == SE_ERR_ACCESSDENIED)
    result = ShellExecuteA( parent, "runas", url, NULL, NULL, SW_SHOWNORMAL );

  // Return whether or not we were successful.
  return ((int)result > 32);
  }

int main( int argc, char** argv )
  {
  // For simple example, just prevent the most basic error.
  if (argc != 2) return 1;

  // (See the end notes about COM objects.)

  // Call our little helper function to do the dirty work.
  open_browser( argv[ 1 ] );

  return 0;
  }

When you compile, make sure to link to shell32. For the GCC, that's

    g++ a.cpp -lshell32

And for VS, that's

    cl a.cpp /link shell32.lib


Now you can see it in action:

    a a.cpp
    a http://www.cplusplus.com

Hope this helps.


End notes:

It is not necessary to initialize COM just to start the user's web browser or open Notepad, but some tasks do use COM components to delegate actions.

For those cases, you will also want to

    #include <objbase.h>

and initialize COM somewhere at the beginning of main() with:

    CoInitializeEx( NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE );

And you will also want to link to ole32.

If you are unsure, just initialize COM anyway.
Topic archived. No new replies allowed.