Introduction
In applications I develop, I often use Microsoft Word to generate various documents
(reports, agendas, invoices, etc). The code to load and shut down the WinWord's COM
server was always the same, so I wrote a simple helper class which manages this.
The Code
using System;
using System.Threading;
using System.Runtime.InteropServices;
namespace AlexKay.Office
{
public class WordLoader : IDisposable
{
private Word.Application wordApp = null;
private bool isNewApp = false;
private bool disposed = false;
public WordLoader()
{
try
{
wordApp = (Word.Application)Marshal.
GetActiveObject("Word.Application");
}
catch
{
wordApp = null;
}
if(wordApp == null)
{
try
{
wordApp = new Word.ApplicationClass();
isNewApp = true;
}
catch
{
wordApp = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
}
if(wordApp != null)
{
try
{
if(isNewApp && wordApp.Documents.Count == 0)
{
object arg1 = Word.WdSaveOptions.
wdDoNotSaveChanges;
object arg2 = null;
object arg3 = null;
wordApp.Quit(ref arg1, ref arg2, ref arg3);
for(;;)
{
Thread.Sleep(100);
try
{
string dummy = wordApp.Version;
}
catch
{
break;
}
}
}
}
catch {}
wordApp = null;
}
}
disposed = true;
}
~WordLoader()
{
Dispose(false);
}
public Word.Application Application
{
get
{
return wordApp;
}
}
}
}
Comments
When the WordLoader
object is created, it checks if the
Word
co-class is already created and registered in the running object table.
If it's not, it creates a new instance of the Word.Application
co-class which loads the
WinWord application. When the WordLoader
object is disposed it
shuts down Word, if it has no documents open.
As you can see, this is quite simple. Any comments on the code are welcome!