How can you open a file with the program associated with its file extension?

前端 未结 6 1538
半阙折子戏
半阙折子戏 2020-12-24 13:50

Is there a simple way to open a file by its associated program in windows? (like double clicking it in windows explorer but done automatically with my code)

For exam

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 14:22

    A little more possibilities here:

    If you want to open - for example - the file by default with Notepad++ (if installed), you could scan for it's registry key if it exists and where it is, (Usually HKLM\SOFTWARE\Wow6432Node\Notepad++ [tested Win7]) then take that path and open it.

    std::wstring file = L"C:\\Outfile.txt";

    if (NotepadPlusPlusExists()) //Open with Notepad++ or use an other program... (maybe your own ?)
    {
        std::wstring wsNPPPath = GetNotepadPlusPlusPath();
        ShellExecuteW(HWND, L"open", wsNPPPath.c_str(), file.c_str(), NULL, SW_NORMAL);
    }
    else //Open with default associated program <---
        ShellExecuteW(HWND, NULL, file.c_str(), NULL, NULL, SW_NORMAL);
    

    If you want the user to be able to change the default program or select a program he/she wants to use, you may open the "Open with" dialog.

    //std::wstring StringArgsW(const wchar_t *format, ...);
    std::wstring wsCmdOpenWith = StringArgsW(L"C:\\Windows\\system32\\shell32.dll,OpenAs_RunDLL \"%s\"", file.c_str());
    ShellExecuteW(HWND, L"open", L"C:\\Windows\\system32\\rundll32.exe", wsCmdOpenWith.c_str(), NULL, SW_NORMAL);
    

    You can also open the file in explorer.

    std::wstring wsCmdExplorer = StringArgsW(L"/select,\"%s\"", file.c_str());
    ShellExecuteW(HWND, L"open", L"explorer.exe", wsCmdExplorer.c_str(), NULL, SW_NORMAL);
    

提交回复
热议问题