如何使用C#设置活动(即前台)Word文档

时间:2013-02-11 22:24:01

标签: c# ms-word

我看过并且未能找到问题的解决方案。我为Word 2007开发了一个附加功能区,它提供了一组额外的加载和保存功能,允许用户从定制系统加载和保存文档。

我的大部分工作 - 当用户请求打开文件时,会将其下载并保存到AppData文件夹,然后打开。但是,我遇到的问题是,如果用户例如打开Word并使用这个新的“加载”功能,空白的Word文档仍然存在,并且Word非常愉快地打开新文档,但它没有获得焦点。

(我在Windows 7上,它在新文档的任务栏中创建了第二个“W”图标,但它没有像我使用正常情况那样切换到Word '开放'路线。)

我尝试过(根据此处其他地方发现的建议)将'visible'属性设置为true,并调用doc.Activate(),但我也不需要。我错过了什么?我用来打开文件的代码如下:

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();
    }
}

(我已经包含了this.Close()因为加载文档的函数保存在一个模态对话框中,并且没有先关闭它,Word会抛出一个关于在打开对话框的情况下切换文档的异常。)

感激不尽的任何帮助!

1 个答案:

答案 0 :(得分:1)

在显示模式对话框时运行此代码会干扰窗口激活。

我不确定这种干扰的确切机制是什么,但修复很简单。将代码移到对话框外。在调用ShowDialog返回后立即执行此代码。