Open a file with its default viewer using Windows API in C
The following will open a file with its default viewer. The behaviour is exactly the same as what will happen when you double click on that file in Explorer.
SHELLEXECUTEINFO lpExecInfo;
memset(&lpExecInfo, 0, sizeof(SHELLEXECUTEINFO));
lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
//name of file to open. For URL, it will be open in the default browser
lpExecInfo.lpFile = L”doc1.doc”;
lpExecInfo.lpParameters = _T(“”);
lpExecInfo.lpDirectory = _T(“”);
lpExecInfo.lpVerb = _T(“open”);
lpExecInfo.fMask = 0;
lpExecInfo.hwnd = g_hwnd; //handle of current window
lpExecInfo.hInstApp = g_hinstModule; //handle to current executable
if (!ShellExecuteEx(&lpExecInfo))
{
//cannot run, show error here
}
Alternatively, use the following to use any program to open a particular file:
PROCESS_INFORMATION pi = {0};
if (!CreateProcess(L”notepad.exe”, L”readme.txt”, NULL, NULL, NULL, 0, NULL, NULL, NULL, &pi))
printf(“Cannot execute process n”);
else
WaitForSingleObject(pi.hProcess, INFINITE);