void KeepNewWindowActivated(Word.Document Doc, Word.Window Wn) { if (newDoc == Doc) { Doc.Activate(); } }
private static void InsertFileIntoDocument(string insertedFile, Word.Application word, Word.Document document, bool BreakPageRequired = true) { document.Activate(); // переключаем фокус на тело документа if (document.ActiveWindow.ActivePane.View.SeekView != Word.WdSeekView.wdSeekMainDocument) document.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument; object missing = Type.Missing; object story = Word.WdUnits.wdStory; word.Selection.EndKey(ref story, ref missing); if (BreakPageRequired == true) { object pageBreak = Word.WdBreakType.wdPageBreak; word.Selection.InsertBreak(ref pageBreak); } object link = false; object attachment = false; object confirm = false; word.Selection.InsertFile(insertedFile, ref missing, ref confirm, ref link, ref attachment); }
private static void ReplaceMailMergeField(Dictionary<string, string> dictionary, Word.Document document, Word.Application word) { word.Visible = false; // обрабатываем верхний коллонтитул ProcessHeaderFooterFields(dictionary, Word.WdSeekView.wdSeekCurrentPageHeader, document, word); // обрабатываем нижний коллонтитул ProcessHeaderFooterFields(dictionary, Word.WdSeekView.wdSeekCurrentPageFooter, document, word); // обработка тела документа ProcessMainDocumentsFields(dictionary, document, word); //ProcessMainFields(dictionary, Word.WdSeekView.wdSeekMainDocument,document, word); if (document.ActiveWindow.ActivePane.View.SeekView != Word.WdSeekView.wdSeekMainDocument) document.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument; word.Visible = true; word.Activate(); }
//--- Intercept save handler void Application_DocumentBeforeSave(Word.Document doc, ref bool SaveAsUI, ref bool Cancel) { //Check if this is one of our docs and if it is then do the right thing, not the black and white thing //Add a document property so we know that is a contract template and what the id is try { bool hidep = false; if (!Globals.ThisAddIn._p.IsVisible) { Globals.ThisAddIn.ProcessingStart("Saving"); hidep = true; } string prop = GetCurrentAxiomDocProp(); if (prop != null) { string[] propa = prop.Split('|'); if (propa[0] == "ContractTemplate") { Globals.ThisAddIn.ProcessingUpdate("Save Contract Template"); // Get the Sidebar and save the elemnt value if that has changed TemplateEdit.TEditSidebar tsb = Globals.ThisAddIn.GetTaskPaneControlTemplate(doc); if(tsb!=null) tsb.FormSave(); //save this to a scratch file Globals.ThisAddIn.ProcessingUpdate("Save Scratch"); string filename = Utility.SaveTempFile(propa[1]); doc.SaveAs2(FileName: filename, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent); //Save a copy! Globals.ThisAddIn.ProcessingUpdate("Save Copy"); string filenamecopy = Utility.SaveTempFile(propa[1] + "X"); Word.Document dcopy = Globals.ThisAddIn.Application.Documents.Add(filename, Visible: false); dcopy.SaveAs2(FileName: filenamecopy, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent); var docclose = (Microsoft.Office.Interop.Word._Document)dcopy; docclose.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(docclose); //Now Globals.ThisAddIn.ProcessingUpdate("Save To SalesForce"); _d.SaveTemplateFile(propa[1], filenamecopy); //d.SaveTemplateXML(propa[1], doc.WordOpenXML); //Cancel the save SaveAsUI = false; Cancel = true; } if (propa[0] == "ClauseTemplate") { //Save! //doc = Globals.ThisAddIn.Application.ActiveDocument; //d.SaveClauseXML(propa[1],doc.Content.Text ,doc.WordOpenXML); Globals.ThisAddIn.ProcessingUpdate("Save Clause Template"); // doc = Globals.ThisAddIn.Application.ActiveDocument; //save this to a scratch file Globals.ThisAddIn.ProcessingUpdate("Save Scratch"); string filename = Utility.SaveTempFile(propa[1]); doc.SaveAs2(FileName: filename, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent); //Save a copy! Globals.ThisAddIn.ProcessingUpdate("Save Copy"); string filenamecopy = Utility.SaveTempFile(propa[1] + "X"); Word.Document dcopy = Globals.ThisAddIn.Application.Documents.Add(filename, Visible: false); dcopy.SaveAs2(FileName: filenamecopy, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent); var docclose = (Microsoft.Office.Interop.Word._Document)dcopy; docclose.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(docclose); //Now save the file and then refresh any other docsto reflect the change Globals.ThisAddIn.ProcessingUpdate("Save To SalesForce"); _d.SaveClauseFile(propa[1], doc.Content.Text, filenamecopy); Globals.ThisAddIn.ProcessingUpdate("Update Any Templates with the clause"); RefreshAllTaskPanesWithClause(propa[1], doc.WordOpenXML); doc.Activate(); //Cancel the save SaveAsUI = false; Cancel = true; } if (propa[0] == "Contract" || propa[0] == "UAContract") { //Save the doc and the data GetTaskPaneControlContract().SaveContract(false,true); //Cancel the save SaveAsUI = false; Cancel = true; } if (propa[0] == "Compare") { //Save the doc and the data GetTaskPaneControlCompare().SaveContract(false, true); //Cancel the save SaveAsUI = false; Cancel = true; } if (hidep) { Globals.ThisAddIn.ProcessingStop("Stop"); } } } catch (Exception e) { Globals.ThisAddIn.ProcessingStop("Stop"); System.Windows.MessageBox.Show("Sorry there has been a problem:"+e.Message); } }
//Contract Instance Stuff - might be the same as ContractTemplate public void UpdateContractConcept(string conceptid, string clauseid, string xml,string lastmodified, Word.Document doc, Dictionary<string, string> elementValues) { //Is it one of ours if (isContract(doc)) { //Remove the handler Microsoft.Office.Tools.Word.Document vstoDoc = Globals.Factory.GetVstoObject(doc); vstoDoc.ContentControlOnExit -= new Word.DocumentEvents2_ContentControlOnExitEventHandler(vstoDoc_ContentControlOnExit); string contractid = GetDocId(doc); //Now step through the doc and update the concept if it matches the one we just updated object start = doc.Content.Start; object end = doc.Content.End; Word.Range r = doc.Range(ref start, ref end); //Create an array of concept content controls in the doc - have to copy or we get into problems with the range including the new ones //that we created Word.ContentControl[] ccs = new Word.ContentControl[r.ContentControls.Count]; int cnt = 0; foreach (Word.ContentControl cc in r.ContentControls) { ccs[cnt++] = cc; } Globals.ThisAddIn.Application.ScreenUpdating = false; //scratch do to hold the clause Word.Document scratch = Application.Documents.Add(Visible: false); //hold the old clauses xml; string oldxml = ""; //Now step through all the Contact Controls and update the XML so we get the newest clauses foreach (Word.ContentControl cc in ccs) { string tag = cc.Tag; if (tag != null && tag != "" && cc.Tag.Contains('|')) { string[] taga = cc.Tag.Split('|'); if (taga[0] == "Concept" && Convert.ToString(taga[1]) == conceptid) { // Get the details of the clause - this would be too chatty when connected to salesforce // store the xml in the tree instead and pass into the function // DataReturn dr = _d.GetClause(clauseid); string txt = ""; if (clauseid!="" && xml == "") { xml = ""; txt = "Sorry! problem clause doesn't exist!"; } if (cc.PlaceholderText != null) { cc.SetPlaceholderText(Text: ""); } // Populate the content control with the values from the database // have to unlock it first cc.LockContents = false; cc.LockContentControl = true; //Also have to unlock any other controls in the range foreach (Word.ContentControl child in cc.Range.ContentControls) { if (child.ID != cc.ID) { child.LockContents = false; child.LockContentControl = false; } } oldxml = cc.Range.WordOpenXML; // OK having lots of problems with large paragraphs inserting into the content // control - had a play manually and it worked when cutting and pasting // *so* get the XML in a sepearate page and then get the formatted text and update // this seems to fix it! need to do some more digging to see if there is a better way Utility.UnlockContentControls(scratch); scratch.Range(scratch.Content.Start, scratch.Content.End).Delete(); if (xml != "") scratch.Range(0).InsertXML(xml); // if clauseid is blank then its a "select none" so do it even though the xml is blank if (clauseid=="" || xml != "") { //cc.Range.InsertXML(xml); //Track changes? if (doc.TrackRevisions) { // OK - gets more complicated! save the old paragraph to a scratch doc and undo any changes // then get the new one in another scratch doc - stop tracking changes in the current doc // do a diff and then insert that in the parra Word.Document oldclause=Globals.ThisAddIn.Application.Documents.Add(Visible: false); string oldclausefilename = Utility.SaveTempFile(doc.Name + "-oldclause"); oldclause.Range().InsertXML(oldxml); // get rid of any changes - have to make it the active doc to do this oldclause.Activate(); oldclause.RejectAllRevisions(); MakeDropDownElementsText(oldclause); // Now update the elements of the scratch Utility.UnlockContentControls(scratch); UpdateElements(scratch, elementValues); // Dropdowns don't diff well (they show as changes, so change the content controls to text - they'll get changed back by initiate) MakeDropDownElementsText(scratch); // Now run a diff - do it from the old doc rather than a compare so it gives us the redline rather than blue line compare string scratchfilename = Utility.SaveTempFile(doc.Name + "-newclause"); scratch.SaveAs2(FileName: scratchfilename, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent); // this is how you do it as a pure compare - Word.Document compare = Application.CompareDocuments(oldclause, scratch,Granularity:Word.WdGranularity.wdGranularityCharLevel); oldclause.Compare(scratchfilename, CompareTarget: Word.WdCompareTarget.wdCompareTargetCurrent, AddToRecentFiles: false); oldclause.ActiveWindow.Visible = false; // Activate the doc - switch of tracking and insert the marked up dif doc.Activate(); doc.TrackRevisions = false; // delete out what is there cc.Range.Delete(); // delete out the styles! cc.Range.set_Style(Word.WdBuiltinStyle.wdStyleNormal); // delete out the pesky tables for (int tablesi = cc.Range.Tables.Count; tablesi > 0; tablesi--) { cc.Range.Tables[tablesi].Delete(); } cc.Range.FormattedText = oldclause.Content.FormattedText; doc.Activate(); doc.TrackRevisions = true; var doccloseoldclause = (Microsoft.Office.Interop.Word._Document)oldclause; doccloseoldclause.Close(false); } else { try { // delete out what is there cc.Range.Delete(); // delete out the styles! cc.Range.set_Style(Word.WdBuiltinStyle.wdStyleNormal); // delete out the pesky tables for (int tablesi = cc.Range.Tables.Count; tablesi > 0; tablesi--) { cc.Range.Tables[tablesi].Delete(); } Word.Range newr = scratch.Range(); cc.Range.FormattedText = newr.FormattedText; } catch (Exception) { } } } else { cc.Range.InsertAfter(txt); } // sort out the formatting problems caused by inserting into the container doc.Activate(); bool tchanges = doc.TrackRevisions; doc.TrackRevisions = false; // When we insert into the clause it adds a \r - have to get rid of it // had a bunch of ways to do it - this seems to work! try { Word.Range newr = doc.Range(cc.Range.End - 1, cc.Range.End); if (newr.Characters.Count == 1) { if (newr.Characters[1].Text == "\r") { // Characters starts at 1 - gets me everytime newr.Delete(); } } } catch (Exception) { } doc.TrackRevisions = tchanges; //close the scratch var docclosescratch = (Microsoft.Office.Interop.Word._Document)scratch; docclosescratch.Close(false); System.Runtime.InteropServices.Marshal.ReleaseComObject(docclosescratch); // update the tag cc.Tag = "Concept|" + conceptid + "|" + clauseid + "|" + lastmodified; //relock cc.LockContents = true; cc.LockContentControl = true; } } } Globals.ThisAddIn.Application.ScreenUpdating = true; //Add back in the handler vstoDoc.ContentControlOnExit += new Word.DocumentEvents2_ContentControlOnExitEventHandler(vstoDoc_ContentControlOnExit); } }
/* void App_NewDocument(Word.Document document) { //System.Windows.Forms.MessageBox.Show("new doc"); log.Debug("New doc event fired."); // new Microsoft.Office.Interop.Word.Document() doesn't make this fire!!! //document.Activate(); } */ /// <summary> /// Create task pane if this docx contains /// XPaths & Conditions parts. /// </summary> /// <param name="document"></param> void App_DocumentOpen(Word.Document document) { // AutoExec macro (if present) and this event will both run, // but where there is an auto exec macro, // only if the user runs the AutoExec macro. // The AutoExec macro runs first, then this. log.Debug("App_DocumentOpen event fired."); //MessageBox.Show("App_DocumentOpen event fired."); if (OpenDoPEDetection.configIfPresent(document)) { log.Debug("OpenDoPE detected"); //MessageBox.Show("OpenDoPE detected"); //Ribbon theRibbon = (Ribbon)Ribbon.getRibbon(); // doesn't work .. can't cast COM object myRibbon.enable(false); //app.WindowBeforeRightClick += new Word.ApplicationEvents4_WindowBeforeRightClickEventHandler(app_WindowBeforeRightClick); } else { //MessageBox.Show("OpenDoPE NOT detected!!"); } document.Activate(); // Set state to match this docx Ribbon.myInvalidate(); log.Debug("Open event handler finished"); }
static void CopyBuildingBlockLogic(Word.Document document, Word.Range Range, FabDocxState fabDocxState) { System.Threading.Thread.Sleep(300); // We need to copy the logic over GlobalTemplateManager.GetGlobalTemplateManager().copyBuildingBlockLogic(document, Range); // If its being copied into a repeat, either: // 1. tell them sorry, can't be done; or // 2. move the repeated variables (and xpaths..) into that repeat! document.Activate(); if (fabDocxState.TaskPane.Visible) { Controls.LogicTaskPaneUserControl ltp = (Controls.LogicTaskPaneUserControl)fabDocxState.TaskPane.Control; ltp.populateLogicInUse(); } }
private static void ReplaceMailMergeField(Dictionary<string, string> dictionary, Word.Document document, Word.Application word) { word.Visible = false; DoReplaceMailMergeField(dictionary, document, word); document.Save(); word.Visible = true; word.Activate(); }