打开文档并等待用户完成编辑

时间:2012-04-07 22:26:08

标签: c# windows events delegates ms-word

我正在尝试以实用方式打开指定的Word文档,然后等待用户完成编辑打开的文档,然后再继续。用户通过关闭窗口来表明他已完成。

但是以下代码不起作用!它一直有效,直到我对文档进行任何编辑:除了等待文档关闭的无限for循环外,所有内容都会冻结。 我该如何解决这个问题?

bool FormatWindowOpen;
    string FormattedText = "";
    MSWord.Application FormattingApp;
    MSWord.Document FormattingDocument;

    private List<string> ImportWords()
    {
        string FileAddress = FileDialogue.FileName;
        FormattingApp = new MSWord.Application();
        FormattingDocument = FormattingApp.Documents.Open(FileAddress);

        FormattingDocument.Content.Text = "Format this document so it contains only the words you want and no other formatting. \nEach word should be on its own line. \nClose the Window when you're done. \nSave the file if you plan to re-use it." + 
                                    "\n" + "----------------------------------------------------------" + "\n" + "\n" + "\n" +
                                    FormattingDocument.Content.Text; //gets rid of formatting as well
        FormattingApp.Visible = true;
        FormattingApp.WindowSelectionChange += delegate { FormattedText = FormattingDocument.Content.Text; };
        FormattingApp.DocumentBeforeClose += delegate { FormatWindowOpen = false; };
        FormatWindowOpen = true;

        for (; ; ){ //waits for the user to finish formating his words correctly
            if (FormatWindowOpen != true) return ExtractWords(FormattedText);
        }
    }

1 个答案:

答案 0 :(得分:1)

你的for循环很可能会冻结你的UI线程。在另一个帖子中启动你的for循环。

以下是使用Rx框架将您的值作为异步数据流返回的示例。

    private IObservable<List<string>> ImportWords()
    {
        Subject<List<string>> contx = new Subject<List<string>>();
        new Thread(new ThreadStart(() =>
            {
                //waits for the user to finish formatting his words correctly
                for (; ; ) 
                { 
                    if (FormatWindowOpen != true) 
                    {
                        contx.OnNext(ExtractWords(FormattedText));
                        contx.OnCompleted();
                        break;
                    }
                }
            })).Start();
        return contx;
    }