Reactive Extension in msword
I am wondering if it is possible to use Reactive Extensions in Word. I have seen this where Jeff shows how to wire up a workbook open event in excel http://social.msdn.microsoft.com/Forums/en/rx/thread/5ace45b1-778b-4ddd-b2ab-d5c8a1659f5f.
I wondering if I could do the same sort of thing in word.
I have got this far....
public static class ApplicationExtensions
{
public static IObservable<Wor开发者_StackOverflow中文版d.Document> DocumentBeforeSaveAsObservable(this Word.Application application)
{
return Observable.Create<Word.Document>(observer =>
{
Word.ApplicationEvents4_DocumentBeforeSaveEventHandler handler = observer.OnNext;
application.DocumentBeforeSave += handler;
return () => application.DocumentBeforeSave -= handler;
});
}
}
but I receive the error No overload for 'OnNext' matches delegate 'Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler
Can anyone point me in the right direction.
Regards
Mike
Your problem is an issue of delegate signatures.
IObserver<T>.OnNext
is defined as void (T value)
whereas ApplicationEvents4_DocumentBeforeSaveEventHandler
is defined as void (Document doc, ref bool SaveAsUI, ref bool Cancel)
If you only need to emit the Document
(and not the other details, like making it cancelable), you can do something like this:
public static IObservable<Word.Document> DocumentBeforeSaveAsObservable(
this Word.Application application)
{
return Observable.Create<Word.Document>(observer =>
{
Word.ApplicationEvents4_DocumentBeforeSaveEventHandler handler =
(doc, ref saveAsUI, ref cancel) => observer.OnNext(doc);
application.DocumentBeforeSave += handler;
return () => application.DocumentBeforeSave -= handler;
});
}
If you do require all the data, you'll need to create a wrapper class of some kind an IObservable
sequence can only emit a single type:
public class DocumentBeforeSaveEventArgs : CancelEventArgs
{
public Document Document { get; private set; }
public bool SaveAsUI { get; private set; }
public DocumentBeforeSaveEventArgs(Document document, bool saveAsUI)
{
this.Document = document;
this.SaveAsUI = saveAsUI;
}
}
And then you can use it like so:
public static IObservable<Word.Document> DocumentBeforeSaveAsObservable(
this Word.Application application)
{
return Observable.Create<Word.Document>(observer =>
{
Word.ApplicationEvents4_DocumentBeforeSaveEventHandler handler =
(doc, ref saveAsUI, ref cancel) =>
{
var args = new DocumentBeforeSaveEventArgs(doc, saveAsUI);
observer.OnNext(args);
cancel = args.Cancel;
};
application.DocumentBeforeSave += handler;
return () => application.DocumentBeforeSave -= handler;
});
}
精彩评论