This project has moved. For the latest updates, please go here.

Make sure window a child of Excel?

Feb 19, 2014 at 3:08 PM
Hello!

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;

//pinvoke
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

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

            Excel.Application excelApplication = null;
            bool result = false;
            try
            {
                excelApplication = Excel.Application.GetActiveInstance();
                if (excelApplication != null)
                {
                    int excelWindowHwnd = excelApplication.Hwnd;
                    result = foregroundWindowHandle == (IntPtr) excelWindowHwnd;
                }
            }
            catch (Exception x)
            {
                result = false;
            }
            finally
            {
                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?