This project has moved and is read-only. For the latest updates, please go here.

Make sure window a child of Excel?

Feb 19, 2014 at 4:08 PM

I have to interact from another program with Excel (get and put some data from and into it, this works already). The interaction gets started by a shortcut (a global hotkey) and then checks if the actual foreground window is a child of Excel.

My first idea was to get the actual foreground window handle and compare that to the one of the 'current' Excel-Application like this:
//using directive to make things shorter ;-)
using Excel = NetOffice.ExcelApi;

static extern IntPtr GetForegroundWindow();

       public static bool ActiveWindowIsExcel()
            IntPtr foregroundWindowHandle = GetForegroundWindow();

            Excel.Application excelApplication = null;
            bool result = false;
                excelApplication = Excel.Application.GetActiveInstance();
                if (excelApplication != null)
                    int excelWindowHwnd = excelApplication.Hwnd;
                    result = foregroundWindowHandle == (IntPtr) excelWindowHwnd;
            catch (Exception x)
                result = false;
                if (excelApplication != null) excelApplication.Dispose();
            return result;
At most times my solution works but sometimes it does not! Usually in the very first start and the very first invocation.

My personal guess is that after GetActiveInstance() is getting only the first of some processes of the ROT (as far as I understand is) and thats not in every case the owner of my current Excel window. Is there a more reliable method to check wether a window is a child of Excel?