The following code is for Windows only.
bool EditFileExternallyBlocking(const TCHAR *FilePathName)
{
SHELLEXECUTEINFO ShellExecuteInfo;
ShellExecuteInfo.cbSize = sizeof(ShellExecuteInfo);
ShellExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShellExecuteInfo.hwnd = NULL;
ShellExecuteInfo.lpVerb = _T("edit");
ShellExecuteInfo.lpFile = FilePathName;
ShellExecuteInfo.lpParameters = NULL;
ShellExecuteInfo.lpDirectory = NULL;
ShellExecuteInfo.nShow = SW_SHOWDEFAULT;
if (!ShellExecuteEx(&ShellExecuteInfo)) {
return false;
}
if (ShellExecuteInfo.hProcess == NULL) {
return false;
}
WaitForSingleObject(ShellExecuteInfo.hProcess, INFINITE);
CloseHandle(ShellExecuteInfo.hProcess);
return true;
}
bool EditFileExternallyPolling(const TCHAR *FilePathName, const std::function<void()> &Callback)
{
SHELLEXECUTEINFO ShellExecuteInfo;
ShellExecuteInfo.cbSize = sizeof(ShellExecuteInfo);
ShellExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShellExecuteInfo.hwnd = NULL;
ShellExecuteInfo.lpVerb = _T("edit");
ShellExecuteInfo.lpFile = FilePathName;
ShellExecuteInfo.lpParameters = NULL;
ShellExecuteInfo.lpDirectory = NULL;
ShellExecuteInfo.nShow = SW_SHOWDEFAULT;
if (!ShellExecuteEx(&ShellExecuteInfo)) {
return false;
}
if (ShellExecuteInfo.hProcess == NULL) {
return false;
}
while (WaitForSingleObject(ShellExecuteInfo.hProcess, 0) == WAIT_TIMEOUT) {
Callback();
}
CloseHandle(ShellExecuteInfo.hProcess);
return true;
}
int main()
{
std::cout << "Blocking way: \n";
std::cout << std::boolalpha << EditFileExternallyBlocking(_T("G:\\test_text_file.txt")) << '\n';
std::cout << "Process has stopped running\n\n";
std::cout << "Polling way: \n";
std::cout << std::boolalpha << EditFileExternallyPolling(_T("G:\\test_text_file.txt"),
[]() {
std::cout << "Process is currently running...\n";
Sleep(1000);
}
) << '\n';
std::cout << "Process has stopped running\n\n";
return 0;
}
Output
Blocking way:
true
Process has stopped running
Polling way:
Process is currently running...
Process is currently running...
Process is currently running...
Process is currently running...
Process is currently running...
Process is currently running...
Process is currently running...
true
Process has stopped running
Other possible return values for WaitForSingleObject
should be handled at release time.
References