关于excel 插件 执行函数GetActiveObject失败的问题
关于excel 插件 执行函数GetActiveObject失败的问题
启动excel之后,执行GetActiveObject失败,经msdn上原因分析如下:
Office 应用程序启动时,它不会立即注册它正在运行的对象。它优化应用程序的启动过程。不在启动时注册 Office 应用程序到在 ROT 中,而是等到它失去焦点的时候才去注册。因此,如果在应用程序失去焦点之前去调用GetActiveObject就会出错。
那么什么时候才调用GetActiveObject呢?微软也提供了一个方法:调用之前加入以下代码:
//Store the handle of the currently active window...
HWND hwndCurrent = ::GetForegroundWindow();
//Launch Excel and wait until it is waiting for
//user input...
STARTUPINFO Start;
PROCESS_INFORMATION ProcInfo;
ZeroMemory(&Start,sizeof(STARTUPINFO));
Start.cb=sizeof(Start);
Start.dwFlags = STARTF_USESHOWWINDOW;
Start.wShowWindow = SW_SHOWMINIMIZED;
//Change the path to Excel as needed...
LPSTR pszExcelPath =
"c:\\program files\\microsoft office\\office\\excel.exe";
::CreateProcess(NULL, pszExcelPath, 0, 0, 1,
NORMAL_PRIORITY_CLASS, 0, NULL, &Start, &ProcInfo);
if((::WaitForInputIdle(ProcInfo.hProcess, 10000))==WAIT_TIMEOUT)
{
::MessageBox(NULL, "Timed out waiting for Excel.", NULL,
MB_OK);
}
//Restore the active window to the foreground...
// NOTE: If you comment out this line, the code will fail!
::SetForegroundWindow(hwndCurrent);
这样相当于是启动另一个进程使当前进程失去焦点,我加入这段代码进去,还是不行。而且我感觉另外创建一个进程的方法对于一个应用程序程序来讲会产生不好的用户体验。各位万能的csdn各位大侠,请求有没有更好的解决方法,不甚感激。