Search code examples
c++glibgtkmmspawn

How to open/spawn a file with glib/gtkmm in Windows


I've already tried:

  GError *pError = NULL;
  string uri = g_filename_to_uri(file.c_str(), NULL, &pError);
  if (!g_app_info_launch_default_for_uri(uri.c_str(), NULL, &pError)) {
      cout << "Failed to open uri: " << pError->message;
  }

Here I get the error "URIs not supported". Is the uri I create here wrong?

My second approach was to spawn the file with an asynchronous command line:

  file = quoteStr(file);
  try {
    Glib::spawn_command_line_async(file);
  } catch (Glib::SpawnError error) {
    cout << error.what();
  } catch (Glib::ShellError error) {
    cout << error.what();
  }

Here the Glib::SpawnError exception is thrown with the error: "Failed to execute helper program (Invalid argument)". I mean, when I execute the quoted absolute file path in the Windows cmd, it opens the file (in this case a pdf file). Does this function work different?


Solution

  • I had a similar problem and I had to give up using glib to do that and ended up implementing a simple crossplatform (win, mac and linux) compatible way to do it:

    // open an URI, different for each operating system
    void
    openuri(const char *url)
    {
    #ifdef WIN32
        ShellExecute(GetActiveWindow(),
             "open", url, NULL, NULL, SW_SHOWNORMAL);
    #elif defined(__APPLE__)
        char buffer[512];
        ::snprintf(buffer, sizeof(buffer), "open %s", url);
        ::system(buffer);
    #else
        char buffer[512];
        ::snprintf(buffer, sizeof(buffer), "xdg-open %s", url);
        ::system(buffer);
    #endif
    }
    

    ... it's not very nice but it's small and it works :)