Reputation: 2517
I'm trying to pragmatically open a specified word document and then wait for the user to finish editing the opened document before moving on. The user indicates that hes done by closing the window.
However the following code will not work! It works until I make any edit to the document: everything just freezes up except the infinite for loop which is waiting for the document to close. How might I fix this?
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);
}
}
Upvotes: 0
Views: 886
Reputation: 17213
Your for loop is most likely freezing up your UI thread. Start your for loop in another thread.
Here is an example using the Rx framework to return your value as an async data stream.
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;
}
Upvotes: 1