1
votes

I have a simple Win Forms application that consists of a Button control, an OpenFileDialog component and a Microsoft.Office.Interop.Word.Application object:

using System;
using System.Windows.Forms;

namespace WordInterop
{
    public partial class Form1 : Form
    {

        // From Form1.Designer.cs:
        //Button openButton;
        //FileOpenDialog openFileDialog;

        private Microsoft.Office.Interop.Word.Application _wordApp;

        public Form1()
        {
            InitializeComponent();
            _wordApp = new Microsoft.Office.Interop.Word.Application();
        }

        protected override void OnClosed(EventArgs e)
        {
            _wordApp.Quit();
            base.OnClosed(e);
        }

        private void _openButton_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog.ShowDialog();
            if (result == DialogResult.OK) {

                 // Throws COMException if Word app is not longer running
                _wordApp.Documents.Open(openFileDialog.FileName);

                _wordApp.Visible = true;
            }
        }
    }
}

When the user clicks the Open button, they can selected a Word document via the OpenFileDialog. The filename of the selected document is used to open the Word Document using the Microsoft.Office.Interop.Word.Application object.

It appears that the Word application is terminated when the user closes the last document: If the user clicks the Open button, selects a document, closes the document, clicks the Open button and selects a document a second time, a COMException occurs with the message The RPC server is unavailable. If there is at least one document open, the user can open documents without a COMException occurring.

Is there a way I can prevent Word application from terminating when the user closes the last document?

I tried creating a hidden blank document by changing the Form1 constructor to the following:

public Form1()
{
    InitializeComponent();
    _wordApp = new Microsoft.Office.Interop.Word.Application();
    _wordApp.Documents.Add(Visible: false);
}

However the blank document becomes visible when the user opens a document meaning it is still possible for user terminate the Word application.

1
Why don't you just add the line _wordApp = new Microsoft.Office.Interop.Word.Application(); to _openButton_Click?waka

1 Answers

0
votes

Create a new instance of Microsoft.Office.Interop.Word.Application() on the button click.

  private void _openButton_Click(object sender, EventArgs e)
    {
        DialogResult result = openFileDialog.ShowDialog();
        if (result == DialogResult.OK) {

            _wordApp = new Microsoft.Office.Interop.Word.Application();
            _wordApp.Documents.Open(openFileDialog.FileName);
            _wordApp.Visible = true;
        }
    }