1

How can I open a file by associated, external program and if it fails call a "open with..." dialog?

Can it be platform independent code? Or I need to use

#ifdef
#else 
#endif 

constructions to implement "open with..." dialog call for every platform?

Thanks in advance

EDIT: Update, after few hours of researching, i found good solution for Windows.

We try to open file with ShellExecute(...), if it fails with file association error, we open file by "open as" Shell32.dll dialog

QString file_path = "C:\VeryGoodPath.txt";
int iResult = (int)ShellExecuteA(0, 0, file_path.toStdString().c_str(), 0, 0 , SW_SHOW );
if(iResult>32)
{
    // Succesful run
}
else
{
    if(SE_ERR_ASSOCINCOMPLETE==iResult)
    {
        QString ShellCmd = "C:\\Windows\\system32\\shell32.dll,OpenAs_RunDLL \""+file_path +"\"";
        ShellExecuteA(0,"open", "C:\\Windows\\system32\\rundll32.exe",ShellCmd.toStdString().c_str(),NULL, SW_NORMAL);
    }
    else
    {
        // Errors
    }
}

EDIT2: Problem was, that i dont use in

 QDesktopServices::openUrl(...)

this function

 QUrl::fromLocalFile("<path_to_your_file>")
Inline
  • 2,566
  • 1
  • 16
  • 32
  • The correct way to invoke the "Open With" dialog on Windows is to pass the target filename to `ShellExecute/Ex()` specifying the `"openas"` verb. Don't call shell32's `OpenAs_RunDLL` directly. See http://stackoverflow.com/questions/6364879/ – Remy Lebeau Mar 22 '16 at 16:29

1 Answers1

4

One easy way is to use QDesktopServices::openUrl:

QDesktopServices::openUrl(QUrl::fromLocalFile("<path_to_your_file>"));

This way you can let the operating system handle it. If a program is associated with that file (or URL in general. You can use this function to open an url in the default browser, too) the operating system will launch it or show the default "Open with" dialog.

Felix
  • 6,885
  • 1
  • 29
  • 54