This is the scenario:
I'm using ShellExecuteEx
in order to open a given .xlsx file. This works fine, Excel is started and the .xlsx file is opened in Excel.
Now ShellExecuteEx
is returning more or less instantly before even Excel has fully started and opened the .xlsx file. So far so good.
Is there a way to wait until the .xlsx file has been actually opened by Excel? Something like a BOOL FileIsOpenExclusively(LPCTSTR filename)
function which returns TRUE is the file is opened exclusively?
Then I could do somehing like this (minimalistic, naïve and non error checking) pseudocode:
ShellExecuteEx(... stuff for opening myfile.xlsx ...);
while (FileIsOpenExclusively("myfile.xlsx"))
{
Sleep(500);
}
// now "myfile.xlsx" is opened execusively
EDITED
The actual slightly more complicated scenario is this:
ShellExecuteEx
launches Excel open the given .xlsx file.- then I need to know somehow when the .xlsx file is closed, either because the file is closed by the Excel user or because the user quits Excel alltogether.
What I'm doing now is illustrated by this pseudo code:
ShellExecuteEx(... stuff for opening myfile.xlsx ...);
Sleep(5000); // wait that Excel has hopefully has opened the file
do
{
Sleep(500);
Open("myfile.xlsx");
} while (opening file is unsuccessful)
// file could be opened which means that Excel has closed it
Close("myfile.xlsx");
The problem is the Sleep(5000);
: if Excel could not open the file within 5.5 seconds, the test below will fail because it will think Excel has closed the file even before it was opened. Therefore I need to know when Excel opens the file rather than waiting a determined amount of time.
Maybe there is another approach. Some comments have suggested to use WaitForInputIdle
which sounds promising, but this may not work if there is already an open instance of Excel beforehand (to be tested).
Another comment suggested enumerating the top-level windows and check for changements of the window title, but I'm not sure this works with modern Excel versions (to be checked) and if it works, it may stop working with the next major Excel version.
Using an oportunistic lock sounds very promising, I'll test this next week.
And finally using the Restart manager might be a lead as well.