Why doesn't Word "come to front" when we activate it?

hawbsl picture hawbsl · Feb 10, 2011 · Viewed 8k times · Source

Our winforms application interacts with MS Word and we run this code when a document is generated and we want to show it in Word in front of our application:

[setup w as a Word interop object]

w.Visible = True
w.Activate()

When rolled out to XP machines running Office 2007 this works as intended.

On Win7 machines running Office 2010 the document loads behind our application and flashes on the taskbar.

Any ideas?

Answer

Christian picture Christian · Feb 10, 2011

I stumbled upon a similar problem recently. My .NET program called a COM application, but on Win7 it would sometimes neither show up in taskbar nor on the desktop at all. I wasn't really able to track down the cause of this, but I wrote the following function to work around the issue:

[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hwnd);

private static void BringAppToFront() {
    foreach (var p in System.Diagnostics.Process.GetProcesses().Where(p => p.ProcessName == "COMInstanceName")) {
        if (p.MainWindowHandle.ToInt32() != 0)
            SetForegroundWindow(p.MainWindowHandle);
    }
}