Code Repo    |     RSS
MD's Technical Sharing



Thursday, March 19, 2009

Open a file with its default viewer:

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);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.