Entwickler582
Entwickler582

Reputation: 73

Set the Focus to Microsoft Word when executed from a C# program

We use Microsoft.Office.Interop.Word to execute Microsoft Word from our Visual C# application. Our problem is about setting the focus to the Microsoft Word window. The problem occurs in Windows 7 only. In Windows 8.1 we have managed to set the focus to the Microsoft Word window. In Windows 7 we haven't: Microsoft Word is only displayed and highlighted in the taskbar but not automatically opened and put to front as a window. I have searched the Internet for solutions to this. There are a lot of threads about this topic, but none of the solutions we tried has led to success.

What we currently do:

After opening the document, we use these lines to display the window.

        word_app.Visible = true;
        word_app.Activate();
        word_app.WindowState = Word.WdWindowState.wdWindowStateMaximize;

To set the focus we write at the end of the method:

        Word.Window window = word_app.ActiveWindow;
        window.SetFocus();
        window.Activate();
        if (window != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(window);

We are waiting for your quick response.

Upvotes: 0

Views: 1549

Answers (2)

Shah Aadil
Shah Aadil

Reputation: 340

I also faced the same problem. And am looking for the answers and applied all kind of solutions unfortunately none works. However the following workaround seems to solve the problem. It just minimizes and maximizes the application object:

application.WindowState = WdWindowState.wdWindowStateMinimize;
application.WindowState = WdWindowState.wdWindowStateMaximize;

Upvotes: 0

Thierry
Thierry

Reputation: 6458

I've always found that the SetForegroundWindow & BringWindowToTop unmanaged API did the trick.

I know it's not ideal, but I don't think there is an actual equivalent in .NET (could be wrong of course, but haven't found it).

This is rather straight forward to use. Check out SetForegroundWindow

Hope this helps.

Upvotes: 1

Related Questions