Open a file with its default viewer using Windows API in C

0.00 avg. rating (0% score) - 0 votes
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.
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:
if (!CreateProcess(L”notepad.exe”, L”readme.txt”, NULL, NULL, NULL, 0, NULL, NULL, NULL, &pi))
printf(“Cannot execute process n”);
WaitForSingleObject(pi.hProcess, INFINITE);
0.00 avg. rating (0% score) - 0 votes


A tough developer who likes to work on just about anything, from software development to electronics, and share his knowledge with the rest of the world.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>