force to bring excel window to the front?

I found this to work. How to bring an Excel app to the front

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);   

public static void BringExcelWindowToFront(Application xlApp)
{

   string caption = xlApp.Caption;
   IntPtr handler = FindWindow(null, caption);
   SetForegroundWindow(handler);
}

Sometimes if there is more than one file open at same time in Excel, ActiveWindow.Activate() will not work.

A successful trick is to do minimize then maximize commands.


some magic, that work for me:

app.WindowState = XlWindowState.xlMinimized; // -4140
app.WindowState = XlWindowState.xlMaximized; // -4137

I would try to activate the excel window by

app.ActiveWindow.Activate();

If this doesn't work you might find other solutions (involving Native WinAPI calls) at this thread at http://social.msdn.microsoft.com/

Tags:

C#

Excel