Chris K
Chris K

Reputation: 540

How to set the active (i.e. foreground) Word document using C#

I have looked and failed to find a solution to my problem. I have developed an Add-in ribbon for Word 2007 which provides an additional set of load and save functions, to allow users to load and save documents from a bespoke system.

I have most of it working - when a user requests a file to be opened, it is downloaded and saved to the AppData folder, and then opened. However, the problem I am having is that if the user for example opens Word and uses this new 'load' function, the blank Word document remains, and Word opens the new document quite happily, but it does not get the focus.

(I'm on Windows 7 and it creates a second 'W' icon in the task bar for the new document, but it doesn't switch to it in the same way that Word would if I'd used the normal 'Open' route.)

I have tried (as a result of suggestions found elsewhere on here) either setting the 'visible' attribute to true, and calling doc.Activate() but neither does what I need. What am I missing? The code I'm using to open the file is below:

private void OK_Click(object sender, EventArgs e)
{
    this.Close();
    FES.FESServices wService = new FES.FESServices();
    int request_id = wService.SubmitRequestFromAddIn(username, password, "RETR", "", textBox1.Text, "", "");
    FES.FileRequestResponse response = wService.GetFileMembersFromAddIn(username, password, request_id);
    if (response.ResponseType == "RETR")
    {
        byte[] data = wService.GetBytesForFilename(response.ResponseValue);
        //MessageBox.Show("Loaded data for file...");
        //MessageBox.Show(Application.UserAppDataPath);
        FileStream fs = new FileStream(Application.UserAppDataPath + "\\" + response.ResponseValue.Substring(6).Split('~')[0], FileMode.Create, FileAccess.Write);
        fs.Write(data, 0, (int)data.Length);
        fs.Close();
        object oMissing = System.Reflection.Missing.Value;

        Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.Documents.Open(
            Application.UserAppDataPath + "\\" + response.ResponseValue.Substring(6).Split('~')[0], Visible:true
        );
        doc.Activate();
    }
}

(I have included this.Close() as the function loading the document is held within a modal dialog box, and without closing it first, Word throws an exception about switching documents with a dialog box open).

Any help gratefully received!

Upvotes: 2

Views: 1666

Answers (1)

David Heffernan
David Heffernan

Reputation: 612844

Running this code whilst the modal dialog is showing is interfering with window activation.

I'm not sure exactly what the mechanism is for this interference, but the fix is simple enough. Move the code outside the dialog. Execute this code immediately after the call to ShowDialog returns.

Upvotes: 2

Related Questions