Click here to Skip to main content
6,295,667 members and growing! (15,251 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Helper class to load WinWord

By Alexander Kojevnikov

Simple class to load/unload WinWord (or any other OLE application)
C#, Windows, .NET 1.0, Visual Studio, Dev
Posted:28 Nov 2002
Views:67,944
Bookmarked:35 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
7 votes for this article.
Popularity: 3.70 Rating: 4.38 out of 5

1

2

3
2 votes, 40.0%
4
3 votes, 60.0%
5

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
{
    /// <summary>

    /// Helper class to manage the Word.Application coclass.

    /// </summary>

    public class WordLoader : IDisposable
    {
        private Word.Application wordApp = null;
        private bool isNewApp = false;

        private bool disposed = false;
        
        public WordLoader()
        {
            // Check if Word is registered in the ROT.

            try
            {
                wordApp = (Word.Application)Marshal.
                    GetActiveObject("Word.Application");
            }
            catch
            {
                wordApp = null;
            }
            // Load Word if it's not.

            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)
                {
                    // Dispose managed resources.

                }
                
                // Dispose unmanaged resources.

                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);

                            // Wait until Word shuts down.

                            for(;;)
                            {
                                Thread.Sleep(100);
                                try
                                {
                                    // When word shuts down this call 

                                    // throws an exception.

                                    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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Alexander Kojevnikov


Member

Occupation: Software Developer (Senior)
Location: Australia Australia

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 18 of 18 (Total in Forum: 18) (Refresh)FirstPrevNext
GeneralSlowly. Pinmember123456uio23:41 5 Feb '07  
GeneralA problem. Pinmembershir123:29 18 Sep '06  
GeneralSuggestion Pinmemberxlg6:59 8 Aug '06  
GeneralSweet PinmemberElNoNo12:13 12 Apr '06  
GeneralWinWord in AxWebBrowser Pinmemberpramod.21c20:17 22 Feb '06  
GeneralDoubt.. PinmemberDevangUdeshi3018221:27 17 Apr '05  
GeneralRe: Doubt.. PinmemberAlexander Kojevnikov10:31 19 Apr '05  
GeneralWordAutomation Examples PinmemberNickle11:14 31 Dec '02  
GeneralRe: WordAutomation Examples PinmemberAlexandre Kojevnikov23:27 3 Feb '03  
GeneralSorry to tell you this... PinmemberDavid Stone12:04 29 Nov '02  
GeneralRe: Sorry to tell you this... PinmemberMarc Clifton13:02 29 Nov '02  
GeneralRe: Sorry to tell you this... PinmemberJörgen Sigvardsson15:04 29 Nov '02  
GeneralRe: Sorry to tell you this... PineditorNishant S16:13 29 Nov '02  
GeneralRe: Sorry to tell you this... PinmemberMarc Clifton13:05 29 Nov '02  
GeneralRe: Sorry to tell you this... PineditorNishant S16:12 29 Nov '02  
GeneralRe: Sorry to tell you this... PinmemberAlex Kay7:47 30 Nov '02  
GeneralRe: Sorry to tell you this... PinmemberDavid Stone14:18 30 Nov '02  
GeneralRe: Sorry to tell you this... Pinmembershofb0:25 2 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Nov 2002
Editor: Smitha Vijayan
Copyright 2002 by Alexander Kojevnikov
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project