I am automating MSWord in a WPF application. Everything working fine, but a Click on Start -> Microsoft word 2010 attaches a new blank document to my instance which is already created by the Wpf application.How restrict this behaviour ?
public partial class MainWindow : System.Windows.Window
{
Word.Application _oApp;
Word.Document _oDoc;
object oMissing = System.Reflection.Missing.Value; // Missing Value
object oTrue = true;
object oFalse = false;
public MainWindow()
{
InitializeComponent();
}
private void btn_Create_Click(object sender, RoutedEventArgs e)
{
_oApp = new Word.Application();
_oApp.Visible = true;
_oApp.ShowWindowsInTaskbar = false;
((Word.ApplicationEvents4_Event)_oApp).NewDocument += new Word.ApplicationEvents4_NewDocumentEventHandler(Application_NewDocument);
}
private void btn_AddDoc_Click(object sender, RoutedEventArgs e)
{
_oDoc = _oApp.Documents.Add(oMissing, oMissing, oMissing);
}
private void btn_RemoveDoc_Click(object sender, RoutedEventArgs e)
{
_oDoc.Close(oFalse, oMissing, oMissing);
}
private void Application_NewDocument(Word.Document doc)
{
MessageBox.Show("New: " + _oApp.ActiveDocument.Name);
}
}
Microsoft listed this as a bug and illustrated a workaround to this problem in the following KB article
BUG: Starting Word Manually Uses Same Instance as Automation - https://support.microsoft.com/en-us/kb/188546
using System.Windows;
using Word = Microsoft.Office.Interop.Word;
namespace WordAutomationTestApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
Word.Application _oApp;
Word.Document _oDoc;
object oMissing = System.Reflection.Missing.Value; // Missing Value
object oTrue = true;
object oFalse = false;
public MainWindow()
{
InitializeComponent();
}
private void btn_Create_Click(object sender, RoutedEventArgs e)
{
//To restrict the automation instance sharing with the user's documents.
//Create a temporary app instance and quit the same after the automation instance is created.
//Ref :: Go through the following work around.
//https://support.microsoft.com/en-us/kb/188546
Word.Application temp = new Word.Application(); //Create temporary instance.
_oApp = new Word.Application(); //Create automation instance.
temp.Quit(oFalse,oMissing,oMissing); //Close the temporary instance.
temp = null;
_oApp.Visible = true;
_oApp.ShowWindowsInTaskbar = false;
((Word.ApplicationEvents4_Event)_oApp).NewDocument += new Word.ApplicationEvents4_NewDocumentEventHandler(Application_NewDocument);
}
private void btn_AddDoc_Click(object sender, RoutedEventArgs e)
{
_oDoc = _oApp.Documents.Add(oMissing, oMissing, oMissing);
}
private void btn_RemoveDoc_Click(object sender, RoutedEventArgs e)
{
_oDoc.Close(oFalse, oMissing, oMissing);
}
private void Application_NewDocument(Word.Document doc)
{
MessageBox.Show("New: " + _oApp.ActiveDocument.Name);
}
}
}
My sincere thanks to @Cindy Meister , for his help to solve this problem.