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

本文关键字:编辑 用户 等待 文档 | 更新日期: 2023-09-27 18:30:27

我正在尝试务实地打开指定的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);
        }
    }

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

你的 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;
    }