Please tell me how to fix the code in c # winforms vs2010 below so that the new word document (oDoc) is created correctly, i.e. if the word application is not yet running, then create a new word, otherwise if it is already running, then create a new document in the already running word application? Now every time you create a word document, another winword.exe process is created.

Word._Application oWord = new Word.Application(); object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; object oTemplate = @"c:\a3.dot"; oWord.Visible = true; oWord.Application.WindowState = Word.WdWindowState.wdWindowStateMinimize; Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing); oDoc.ActiveWindow.WindowState = Word.WdWindowState.wdWindowStateMaximize; 

    1 answer 1

     using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WorkTime_v5 { public class WordInstanceSingleton { private static Microsoft.Office.Interop.Word.Application m_wordInstance; private WordInstanceSingleton() { } public static Microsoft.Office.Interop.Word.Application Instance { get { if (m_wordInstance == null) { m_wordInstance = new Microsoft.Office.Interop.Word.Application(); } return m_wordInstance; } } } } private void btn_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Word.Application oWord = WordInstanceSingleton.Instance; object oTemplate = @"c:\a3.dot"; Microsoft.Office.Interop.Word.Document doc; object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; try { oWord.Visible = true; doc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing); } catch { MessageBox.Show("Ошибка!"); return; } oWord.Application.WindowState = Word.WdWindowState.wdWindowStateMinimize; doc.ActiveWindow.WindowState = Word.WdWindowState.wdWindowStateMinimize; //... doc.ActiveWindow.WindowState = Word.WdWindowState.wdWindowStateMaximize; doc.Activate(); oWord.Activate(); 
    • The code above works, but if, while the program is running, you close all the created word windows (to create new ones), then MessageBox.Show ("Error!"). Please tell me how to fix the code above. - olga