/// <summary>
 /// Replaces all the symbols with the proper coloring
 /// </summary>
 /// <param name="PobjDoc"></param>
 private void colorCode(Word.Document PobjDoc)
 {
     try
     {
         // now find all the symbols and color code them
         foreach (ExtendedRecipient LobjRecipient in MobjSettings.Recipients)
         {
             Word.Find LobjFind = PobjDoc.Range().Find;
             // Clear all previously set formatting for Find dialog box.
             LobjFind.ClearFormatting();
             // Clear all previously set formatting for Replace dialog box.
             LobjFind.Replacement.ClearFormatting();
             // Set font to Replace found font.
             LobjFind.Text                   = LobjRecipient.Symbol;
             LobjFind.Forward                = true;
             LobjFind.Wrap                   = Word.WdFindWrap.wdFindContinue;
             LobjFind.Format                 = true;
             LobjFind.MatchCase              = true;
             LobjFind.MatchWholeWord         = false;
             LobjFind.MatchWildcards         = false;
             LobjFind.MatchSoundsLike        = false;
             LobjFind.MatchAllWordForms      = false;
             LobjFind.Replacement.Text       = LobjRecipient.Symbol;
             LobjFind.Replacement.Font.Color = LobjRecipient.HighlightColor.FromRGBColorString().ConvertToWordColor();
             LobjFind.Execute(Replace: Word.WdReplace.wdReplaceAll);
         }
     }
     catch (Exception PobjEx)
     {
         PobjEx.Log(true, "Unable to update the coloring on the symbols.");
     }
 }
        public void RemplazarImagen(string textoReemplazar, string imagenReemplazo)
        {
            //Word.Document documentoActivo = new Word.Document();
            Object nullobj = Type.Missing;
            Object start   = 0;
            Object end     = aDoc.Characters.Count;

            Word.Range rng = aDoc.Range(ref start, ref end);
            Word.Find  fnd = rng.Find;

            fnd.ClearFormatting();

            fnd.Text    = textoReemplazar;
            fnd.Forward = true;

            Object linktoFile  = false;
            Object SaveWithDoc = true;


            Object replaceOption = Word.WdReplace.wdReplaceOne;
            Object range         = Type.Missing;

            fnd.Execute(ref nullobj, ref nullobj, ref nullobj, ref nullobj,
                        ref nullobj, ref nullobj, ref nullobj, ref nullobj,
                        ref nullobj, ref nullobj, ref replaceOption, ref nullobj,
                        ref nullobj, ref nullobj, ref nullobj);

            //Insertamos la imagen en la posicion adecuada
            rng.InlineShapes.AddPicture(imagenReemplazo, ref linktoFile, ref SaveWithDoc, ref range);
        }
Beispiel #3
0
        public void PrintDoc()
        {
            try
            {
                Word.Application word     = new Word.Application();
                Word.Document    document = new Word.Document();
                document = word.Documents.Open(_docpath, ReadOnly: false, Visible: false);
                document.Activate();

                Word.Find find = word.Selection.Find;
                find.ClearFormatting();
                find.Replacement.ClearFormatting();
                object replaceAll = Word.WdReplace.wdReplaceAll;
                object missing    = System.Type.Missing;

                BookmarkSubroutine(document, "username", _username, 0);
                BookmarkSubroutine(document, "password", _password, 0);
                BookmarkSubroutine(document, "notes", _notes, 0);

                document.PrintOut();
                document.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                word.Application.Quit();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Beispiel #4
0
        public void InterpretHighlightTags(Word.Application appWord, Word.Document doc)
        {
            Word.Range        rng = doc.Content;
            Word.Find         f   = rng.Find;
            Word.WdColorIndex old = appWord.Options.DefaultHighlightColorIndex;

            appWord.Options.DefaultHighlightColorIndex = Word.WdColorIndex.wdYellow;
            f.Replacement.ClearFormatting();
            f.Replacement.Highlight = 1;
            FindAndReplace(doc, "\\[yellow\\](*)\\[/yellow\\]", f);

            appWord.Options.DefaultHighlightColorIndex = Word.WdColorIndex.wdBrightGreen;
            f.Replacement.ClearFormatting();
            f.Replacement.Highlight = 1;
            FindAndReplace(doc, "\\[brightgreen\\](*)\\[/brightgreen\\]", f);

            appWord.Options.DefaultHighlightColorIndex = Word.WdColorIndex.wdTurquoise;
            f.Replacement.ClearFormatting();
            f.Replacement.Highlight = 1;
            FindAndReplace(doc, "\\[t\\](*)\\[/t\\]", f);

            f.Replacement.ClearFormatting();
            f.Replacement.Font.StrikeThrough = 1;
            FindAndReplace(doc, "\\[s\\](*)\\[/s\\]", f);

            // reset options
            f.Replacement.Highlight = 0;
            appWord.Options.DefaultHighlightColorIndex = old;
        }
Beispiel #5
0
        public void SwapText(params string[] marks)
        {
            bool rangeFound;

            Word.Range wordRange;
            foreach (string mark in marks)
            {
                rangeFound = false;
                for (int i = 1; i <= document.Sections.Count; i++)
                {
                    wordRange = document.Sections[i].Range;
                    Word.Find wordFindObj        = wordRange.Find;
                    object[]  wordFindParameters = new object[15]
                    {
                        mark, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj,
                        missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj
                    };
                    rangeFound = (bool)wordFindObj.GetType().InvokeMember
                                     ("Execute", BindingFlags.InvokeMethod, null, wordFindObj, wordFindParameters);
                    if (rangeFound)
                    {
                        wordRange.Text = sr.ReadLine();
                        break;
                    }
                }
            }
        }
        public void replace(string toFind, string toReplace)
        {
            if (Closed)
            {
                throw new Exception("Документ уже закрыт");
            }

            object toFindObj    = toFind;
            object toReplaceObj = toReplace;

            Word.Range wordRange;
            object     typeOfFindAndRep = Word.WdReplace.wdReplaceAll;

            try
            {
                for (int i = 1; i <= _document.Sections.Count; i++)
                {
                    wordRange = _document.Sections[i].Range;
                    Word.Find wordFindObj    = wordRange.Find;
                    object[]  wordFindParams = new object[15] {
                        toFindObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, toReplaceObj,
                        typeOfFindAndRep, _missingObj, _missingObj, _missingObj, _missingObj
                    };
                    wordFindObj.GetType().InvokeMember("Execute", System.Reflection.BindingFlags.InvokeMethod, null, wordFindObj, wordFindParams);
                }
            }
            catch (Exception e)
            {
                throw new Exception("Ошибка при замене строк\n" + e.Message);
            }
        }
        private Word.Find CreateFind(Word.Range range, string text)
        {
            Word.Find result = range.Find;
            result.Execute(FindText: text, Forward: true, Wrap: Word.WdFindWrap.wdFindStop);

            return(result);
        }
Beispiel #8
0
        private bool ExecuteReplace(Word.Find find, object replaceOption)
        {
            object findText          = Type.Missing;
            object matchCase         = Type.Missing;
            object matchWholeWord    = Type.Missing;
            object matchWildcards    = Type.Missing;
            object matchSoundsLike   = Type.Missing;
            object matchAllWordForms = Type.Missing;
            object forward           = Type.Missing;
            object wrap            = Type.Missing;
            object format          = Type.Missing;
            object replaceWith     = Type.Missing;
            object matchKashida    = Type.Missing;
            object matchDiacritics = Type.Missing;
            object matchAlefHamza  = Type.Missing;
            object matchControl    = Type.Missing;

            return(find.Execute(
                       ref findText, ref matchCase,
                       ref matchWholeWord, ref matchWildcards,
                       ref matchSoundsLike, ref matchAllWordForms,
                       ref forward, ref wrap,
                       ref format, ref replaceWith,
                       ref replaceOption, ref matchKashida,
                       ref matchDiacritics, ref matchAlefHamza, ref matchControl
                       ));
        }
Beispiel #9
0
        private void SearchReplace(string SearchFor, string ReplaceWith, word.Application wordApp)
        {
            word.Find findObj = wordApp.Selection.Find;
            findObj.ClearFormatting();
            findObj.Text = SearchFor;
            findObj.Replacement.ClearFormatting();
            findObj.Replacement.Text = ReplaceWith;

            object missing = System.Reflection.Missing.Value;

            object replace = word.WdReplace.wdReplaceOne;

            findObj.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing, ref missing,
                            ref replace, ref missing, ref missing, ref missing, ref missing);

            //same thing as clicking away from a selection
            wordApp.Selection.Collapse();

            //put the cursor at start of document or find won't work.
            Object toWhat  = word.WdGoToItem.wdGoToLine;
            Object toWhich = word.WdGoToDirection.wdGoToFirst;

            wordApp.Selection.GoTo(toWhat, toWhich, ref missing, ref missing);
        }
        public bool FindNext(string text)
        {
            Word.Selection selecao    = Globals.ThisAddIn.Application.Selection;
            Word.Document  doc        = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Selection selection  = Globals.ThisAddIn.Application.ActiveDocument.Application.Selection;
            Word.Find      findObject = Globals.ThisAddIn.Application.Selection.Find;

            object findText = text;

            selection.Find.ClearFormatting();
            selection.Find.Forward   = true;
            selection.Find.MatchCase = false;
            selection.Find.Execute(ref findText);

            if (!selection.Find.Found)
            {
                doc.Range(0, 0).Select();
                selection.Find.Execute(ref findText);
                if (!selection.Find.Found)
                {
                    return(false);
                }
            }
            return(true);
        }
        /// <summary>
        /// Поиск строки внутри Range, при успехе возвращает Range  для этой строки
        /// </summary>
        /// <param name="containerRange"></param>
        /// <param name="stringToFind"></param>
        /// <returns></returns>
        private Word.Range findRangeByString(Word.Range containerRange, string stringToFind)
        {
            // проверяем, не закрыт ли документ или приложение ворд
            if (Closed)
            {
                throw new Exception("Ошибка при обращении к документу Word. Документ уже закрыт.");
            }
            // оформляем обьектные параметры
            object stringToFindObj = stringToFind;
            bool   rangeFound;

            /*
             * Обходим редкий глюк в Find, ПРИЗНАННЫЙ MICROSOFT, метод Execute на некоторых машинах вылетает с ошибкой "Заглушке переданы неправильные данные / Stub received bad data"
             * http://support.microsoft.com/default.aspx?scid=kb;en-us;313104
             * rangeFound = containerRange.Find.Execute(ref stringToFindObj, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing);
             */

            Word.Find wordFindObj = containerRange.Find;

            object[] wordFindParameters = new object[15] {
                stringToFindObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj
            };

            rangeFound = (bool)wordFindObj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, wordFindObj, wordFindParameters);


            if (rangeFound)
            {
                return(containerRange);
            }
            else
            {
                return(null);
            }
        }
Beispiel #12
0
        public void InterpretFontTags(Word.Application appWord, Word.Document doc)
        {
            Word.Range rng = doc.Content;
            Word.Find  f   = rng.Find;
            appWord.Visible = true;
            // Font options
            f.Replacement.ClearFormatting();
            f.Replacement.Font.Bold = 1;
            FindAndReplace(doc, "\\<strong\\>(*)\\</strong\\>", f);

            f.Replacement.ClearFormatting();
            f.Replacement.Font.Italic = 1;
            FindAndReplace(doc, "\\<em\\>(*)\\</em\\>", f);

            f.Replacement.ClearFormatting();
            f.Replacement.Font.Underline = Word.WdUnderline.wdUnderlineSingle;
            FindAndReplace(doc, "\\<u\\>(*)\\</u\\>", f);

            // Font colors
            f.Replacement.ClearFormatting();
            f.Replacement.Font.Color = Word.WdColor.wdColorLightBlue;
            FindAndReplace(doc, "\\<lblue\\>(*)\\</lblue\\>", f);

            f.Replacement.ClearFormatting();
            f.Replacement.Font.Color = Word.WdColor.wdColorRed;
            FindAndReplace(doc, "\\<red\\>(*)\\</red\\>", f);

            f.Replacement.ClearFormatting();
            f.Replacement.Font.Color = Word.WdColor.wdColorGray35;
            FindAndReplace(doc, "\\<gray\\>(*)\\</gray\\>", f);

            // tracked changes tags
        }
Beispiel #13
0
        public void FormatFormula(bool formatAll = false)
        {
            this.Application.Selection.ShrinkDiscontiguousSelection();
            var currRange = this.Application.Selection.Range;
            var currText  = currRange.Text.Trim();



            if (formatAll)
            {
                object     findText = currText;
                Word.Range rng      = this.Application.ActiveDocument.Content;
                Word.Find  rngFind  = rng.Find;
                rngFind.Forward = true;

                do
                {
                    rngFind.ClearFormatting();
                    if (rngFind.Execute(FindText: ref findText))
                    {
                        if (!FormatFormulaAt(rng.Start, currText))
                        {
                            return;
                        }
                        rng.SetRange(rng.End, this.Application.ActiveDocument.Content.End);
                    }
                }while (rngFind.Found);
            }
            else
            {
                FormatFormulaAt(currRange.Start, currText);
            }
        }
Beispiel #14
0
        public static void findNext(string txt, bool caseSens)
        {
            Word.Selection selecao    = Globals.ThisAddIn.Application.Selection;
            Word.Document  doc        = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Selection selection  = Globals.ThisAddIn.Application.ActiveDocument.Application.Selection;
            Word.Find      findObject = Globals.ThisAddIn.Application.Selection.Find;


            object findText = txt;

            selection.Find.ClearFormatting();
            selection.Find.Forward   = true;
            selection.Find.MatchCase = caseSens;
            selection.Find.Execute(ref findText);

            if (!selection.Find.Found)
            {
                doc.Range(0, 0).Select();
                selection.Find.Execute(ref findText);
                if (!selection.Find.Found)
                {
                    MessageBox.Show("Nenhuma ocorrência encontrada!");
                }
            }
        }
Beispiel #15
0
        public void FindAndReplace(string findText, string replaceText)
        {
            // обьектные строки для Word
            object strToFindObj  = "{" + findText + "}";
            object replaceStrObj = replaceText;

            //тип поиска и замены
            object replaceTypeObj;

            replaceTypeObj = Word.WdReplace.wdReplaceAll;

            // обходим все разделы документа
            for (int i = 1; i <= document.Sections.Count; i++)
            {
                // берем всю секцию диапазоном
                wordRange = document.Sections[i].Range;

                Word.Find wordFindObj = wordRange.Find;

                object[] wordFindParameters = new object[15] {
                    strToFindObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, replaceStrObj, replaceTypeObj, missingObj, missingObj, missingObj, missingObj
                };

                wordFindObj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, wordFindObj, wordFindParameters);
            }
        }
        private void ReplaceWord(string phrase, string replacementWord, bool indexWordsOnly)
        {
            AddinHelper.Common.WriteToDebugWindow(String.Format("phrase:>{0}<  indexWordsOnly:{1}", phrase, indexWordsOnly));

            Globals.ThisAddIn.Application.Selection.Find.ClearFormatting();

            if (indexWordsOnly)
            {
                Globals.ThisAddIn.Application.Selection.Find.set_Style(Globals.ThisAddIn.Application.ActiveDocument.Styles[cINDEX_WORD_STYLE]);
            }

            Globals.ThisAddIn.Application.Selection.Find.Replacement.ClearFormatting();

            Microsoft.Office.Interop.Word.Find findObj = Globals.ThisAddIn.Application.Selection.Find;

            findObj.Text              = phrase;
            findObj.Replacement.Text  = replacementWord;
            findObj.Forward           = true;
            findObj.Wrap              = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
            findObj.Format            = true;
            findObj.MatchCase         = false;
            findObj.MatchWholeWord    = false;
            findObj.MatchWildcards    = false;
            findObj.MatchSoundsLike   = false;
            findObj.MatchAllWordForms = false;

            findObj.Execute(Replace: Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll);
        }
Beispiel #17
0
        Word.Range SearchRange(string stringToFind)
        {
            object stringToFindObj = stringToFind;

            Word.Range wordRange;
            bool       rangeFound;

            for (int i = 1; i <= document.Sections.Count; i++)
            {
                wordRange = document.Sections[i].Range;
                Word.Find wordFindObj        = wordRange.Find;
                object[]  wordFindParameters = new object[15] {
                    stringToFindObj, missingObj, missingObj, missingObj,
                    missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj,
                    missingObj, missingObj, missingObj
                };
                rangeFound = (bool)wordFindObj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null,
                                                                      wordFindObj, wordFindParameters);
                if (rangeFound)
                {
                    return(wordRange);
                }
            }
            return(null);
        }
Beispiel #18
0
        private Boolean ExecuteReplace(Microsoft.Office.Interop.Word.
                                       Find find, Object replaceOption)
        {
            Object findText          = Type.Missing;
            Object matchCase         = Type.Missing;
            Object matchWholeWord    = Type.Missing;
            Object matchWildcards    = Type.Missing;
            Object matchSoundsLike   = Type.Missing;
            Object matchAllWordForms = Type.Missing;
            Object forward           = Type.Missing;
            Object wrap            = Type.Missing;
            Object format          = Type.Missing;
            Object replaceWith     = Type.Missing;
            Object replace         = replaceOption;
            Object matchKashida    = Type.Missing;
            Object matchDiacritics = Type.Missing;
            Object matchAlefHamza  = Type.Missing;
            Object matchControl    = Type.Missing;

            return(find.Execute(ref findText, ref matchCase,
                                ref matchWholeWord, ref matchWildcards, ref matchSoundsLike,
                                ref matchAllWordForms, ref forward, ref wrap, ref format,
                                ref replaceWith, ref replace, ref matchKashida,
                                ref matchDiacritics, ref matchAlefHamza, ref matchControl));
        }
Beispiel #19
0
        public static int FindText(Word.Document doc, string text)
        {
            int count = 0;

            Word.Find find = doc.Application.Selection.Find;
            find.ClearFormatting();
            find.Text              = text;
            find.Replacement.Text  = "";
            find.Forward           = true;
            find.Wrap              = Word.WdFindWrap.wdFindContinue;
            find.Format            = false;
            find.MatchCase         = true;
            find.MatchWholeWord    = false;
            find.MatchByte         = true;
            find.MatchWildcards    = false;
            find.MatchSoundsLike   = false;
            find.MatchAllWordForms = false;

            doc.Range(0, 0).Select();
            while (find.Execute())
            {
                count++;
            }
            return(count);
        }
        private void StringReplace(Word._Document document, string strToFind, string replaceStr)
        {
            Object missingObj = Missing.Value;
            // обьектные строки для Word
            object strToFindObj  = strToFind;
            object replaceStrObj = replaceStr;

            // диапазон документа Word
            Word.Range wordRange;
            //тип поиска и замены
            object replaceTypeObj = Word.WdReplace.wdReplaceAll;

            // обходим все разделы документа
            for (int i = 1; i <= document.Sections.Count; i++)
            {
                // берем всю секцию диапазоном
                wordRange = document.Sections[i].Range;

                /*
                 * Обходим редкий глюк в Find, ПРИЗНАННЫЙ MICROSOFT, метод Execute на некоторых машинах вылетает с ошибкой "Заглушке переданы неправильные данные / Stub received bad data"  Подробности: http://support.microsoft.com/default.aspx?scid=kb;en-us;313104
                 * // выполняем метод поиска и  замены обьекта диапазона ворд
                 * wordRange.Find.Execute(ref strToFindObj, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref replaceStrObj, ref replaceTypeObj, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing);
                 */

                Word.Find wordFindObj        = wordRange.Find;
                object[]  wordFindParameters = new object[15] {
                    strToFindObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, missingObj, replaceStrObj, replaceTypeObj, missingObj, missingObj, missingObj, missingObj
                };

                wordFindObj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, wordFindObj, wordFindParameters);
            }
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                return;
            }

            Word.Application app      = new Word.Application();
            Object           fileName = args[0];
            Object           missing  = Type.Missing;

            app.Documents.Open(ref fileName);
            Word.Find find = app.Selection.Find;
            find.Text             = "#Date#";
            find.Replacement.Text = DateTime.Today.ToString();
            Object wrap    = Word.WdFindWrap.wdFindContinue;
            Object replace = Word.WdReplace.wdReplaceAll;

            find.Execute(FindText: Type.Missing,
                         MatchCase: false,
                         MatchWholeWord: false,
                         MatchWildcards: false,
                         MatchSoundsLike: missing,
                         MatchAllWordForms: false,
                         Forward: true,
                         Wrap: wrap,
                         Format: false,
                         ReplaceWith: missing, Replace: replace);
            app.ActiveDocument.Save();
            app.ActiveDocument.Close();
            app.Quit();
        }
Beispiel #22
0
        public void Replace(string oldText, string newText)
        {
            object strToFindObj  = oldText;
            object replaceStrObj = newText;

            Word.Range wordRange;
            object     replaceTypeObj;

            replaceTypeObj = Word.WdReplace.wdReplaceAll;

            for (int i = 1; i <= document.Sections.Count; i++)
            {
                wordRange = document.Sections[i].Range;

                /*
                 * Обходим редкий глюк в Find, ПРИЗНАННЫЙ MICROSOFT, метод Execute на некоторых машинах вылетает с ошибкой "Заглушке переданы неправильные данные / Stub received bad data"  Подробности: http://support.microsoft.com/default.aspx?scid=kb;en-us;313104
                 * // выполняем метод поиска и  замены обьекта диапазона ворд
                 * wordRange.Find.Execute(ref strToFindObj, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref replaceStrObj, ref replaceTypeObj, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing);
                 */

                Word.Find wordFindObj        = wordRange.Find;
                object[]  wordFindParameters = new object[15] {
                    strToFindObj, missingObj,
                    missingObj, missingObj, missingObj, missingObj,
                    missingObj, missingObj, missingObj, replaceStrObj, replaceTypeObj,
                    missingObj, missingObj, missingObj, missingObj
                };

                wordFindObj.GetType().
                InvokeMember("Execute", BindingFlags.InvokeMethod, null, wordFindObj, wordFindParameters);
            }
        }
Beispiel #23
0
 public WordTextEditor()
 {
     application = new Application();
     Microsoft.Office.Interop.Word.Document document = application.Documents.Open(@"C:\Users\tomer\Desktop\Yael\Test\Test1.docx");
     fnd = application.ActiveWindow.Selection.Find;
     int x = 1;
 }
Beispiel #24
0
        private void dgvComments_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            string id = dgvComments[0, e.RowIndex].Value.ToString();

            Word.Document doc  = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Find     find = doc.Content.Find;
            find.ClearHitHighlight();
            find.HitHighlight(FindText: id, MatchCase: true, HighlightColor: Word.WdColor.wdColorYellow, MatchWholeWord: true);
        }
Beispiel #25
0
        /// <summary>
        /// Finds the next redaction mark in current document story range (e.g. the current text box).
        /// </summary>
        /// <param name="CurrentRange">The range containing the starting point of the search. Changes to the location of the output mark if one is found.</param>
        /// <returns>True if a mark was found, otherwise False.</returns>
        private static bool FindNextMarkInCurrentStoryRange(ref Word.Range CurrentRange)
        {
            object Missing = Type.Missing;

            Word.Find FindScope = CurrentRange.Find;
            FindScope.Font.Shading.BackgroundPatternColor = ShadingColor;

            return(FindScope.ExecuteOld(ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing));
        }
Beispiel #26
0
 public bool isExist()
 {
     wdFind = wdApp.Selection.Find;
     wdFind.ClearFormatting();
     wdFind.Text = "[" + beginOfSearchingMask + "]*[" + endOfSearchingMask + "]";
     wdFind.Replacement.ClearFormatting();
     wdFind.MatchWildcards = true;
     return(wdFind.Execute());
 }
 private void btn_Begin_Click(object sender, EventArgs e)
 {
     btn_Begin.Enabled = false;                                       //停用替换按钮
     ThreadPool.QueueUserWorkItem(                                    //开始线程池
         (o) =>                                                       //使用Lambda表达式
     {
         G_WordApplication =                                          //创建Word应用程序对象
                             new Microsoft.Office.Interop.Word.Application();
         object P_FilePath        = G_OpenFileDialog.FileName;        //创建Object对象
         Word.Document P_Document = G_WordApplication.Documents.Open( //打开Word文档
             ref P_FilePath, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing);
         Word.Range P_Range =                            //得到文档范围
                              P_Document.Range(ref G_Missing, ref G_Missing);
         Word.Find P_Find =                              //得到Find对象
                            P_Range.Find;
         this.Invoke(                                    //在窗体线程中执行
             (MethodInvoker)(() =>                       //使用Lambda表达式
         {
             P_Find.Text = txt_Find.Text;                //设置查找的文本
             P_Find.Replacement.Text = txt_Replace.Text; //设置替换的文本
         }));
         object P_Replace = Word.WdReplace.wdReplaceAll; //定义替换方式对象
         bool P_bl        = P_Find.Execute(              //开始替换
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing, ref P_Replace,
             ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing);
         G_WordApplication.Documents.Save(            //保存文档
             ref G_Missing, ref G_Missing);
         ((Word._Document)P_Document).Close(          //关闭文档
             ref G_Missing, ref G_Missing, ref G_Missing);
         ((Word._Application)G_WordApplication).Quit( //退出Word应用程序
             ref G_Missing, ref G_Missing, ref G_Missing);
         this.Invoke(                                 //在窗体线程中执行
             (MethodInvoker)(() =>                    //使用Lambda表达式
         {
             if (P_bl)                                //查看是否找到并替换
             {
                 MessageBox.Show(                     //弹出消息对话框
                     "找到字符串并替换", "提示!");
                 btn_Display.Enabled = true;          //启用显示文件按钮
             }
             else
             {
                 MessageBox.Show(        //弹出消息对话框
                     "没有找到字符串", "提示!");
             }
             btn_Begin.Enabled = true;        //启用开始替换按钮
         }));
     });
 }
 private void btn_Begin_Click(object sender, EventArgs e)
 {
     btn_Begin.Enabled = false;                                       //停用替換按鈕
     ThreadPool.QueueUserWorkItem(                                    //開始線程池
         (o) =>                                                       //使用Lambda表達式
     {
         G_WordApplication =                                          //建立Word應用程式物件
                             new Microsoft.Office.Interop.Word.Application();
         object P_FilePath        = G_OpenFileDialog.FileName;        //建立Object物件
         Word.Document P_Document = G_WordApplication.Documents.Open( //打開Word文件檔
             ref P_FilePath, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing);
         Word.Range P_Range =                            //得到文件檔範圍
                              P_Document.Range(ref G_Missing, ref G_Missing);
         Word.Find P_Find =                              //得到Find物件
                            P_Range.Find;
         this.Invoke(                                    //在視窗線程中執行
             (MethodInvoker)(() =>                       //使用Lambda表達式
         {
             P_Find.Text = txt_Find.Text;                //設定搜尋的文字
             P_Find.Replacement.Text = txt_Replace.Text; //設定替換的文字
         }));
         object P_Replace = Word.WdReplace.wdReplaceAll; //定義替換方式物件
         bool P_bl        = P_Find.Execute(              //開始替換
             ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing,
             ref G_Missing, ref G_Missing, ref G_Missing, ref P_Replace,
             ref G_Missing, ref G_Missing, ref G_Missing, ref G_Missing);
         G_WordApplication.Documents.Save(            //儲存文件檔
             ref G_Missing, ref G_Missing);
         ((Word._Document)P_Document).Close(          //關閉文件檔
             ref G_Missing, ref G_Missing, ref G_Missing);
         ((Word._Application)G_WordApplication).Quit( //退出Word應用程式
             ref G_Missing, ref G_Missing, ref G_Missing);
         this.Invoke(                                 //在視窗線程中執行
             (MethodInvoker)(() =>                    //使用Lambda表達式
         {
             if (P_bl)                                //查看是否找到並替換
             {
                 MessageBox.Show(                     //彈出消息對話框
                     "找到字串並替換", "提示!");
                 btn_Display.Enabled = true;          //啟用顯示文件按鈕
             }
             else
             {
                 MessageBox.Show(        //彈出消息對話框
                     "沒有找到字串", "提示!");
             }
             btn_Begin.Enabled = true;        //啟用開始替換按鈕
         }));
     });
 }
Beispiel #29
0
        private void run_replace(WORD.Find find, string src, string dest)
        {
            object objMissing = Type.Missing;

            find.Text             = src;
            find.Replacement.Text = dest;
            find.Execute(ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                         ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref myReplace,
                         ref objMissing, ref objMissing, ref objMissing, ref objMissing);
        }
Beispiel #30
0
        private void FindReplace(string FieldText, string FieldValue)
        {
            Word.Find findObject = oWord.Selection.Find;

            findObject.Text = FieldText;
            findObject.ClearFormatting();


            switch (FieldText)
            {
            case "Organization":
                findObject.Text = "<Organization>";
                break;

            case "BCRS":
                findObject.Text = "<T_SCORES_BCRS%>";
                break;

            case "AC":
                findObject.Text = "<T_SCORES_AC>";
                break;

            case "AAP":
                findObject.Text = "<T_SCORES_AAP>";
                break;

            case "IVC":
                findObject.Text = "<" + "T_SCORES_IVC" + ">";
                break;

            case "SI":
                findObject.Text = "<" + "T_SCORES_SI" + ">";
                break;

            case "DC":
                findObject.Text = "<" + "T_SCORES_DC" + ">";
                break;

            case "MATRIX LABEL":
                findObject.Text = "<" + "T_SCORES_MATLABEL" + ">";
                break;

            default:
                System.Console.WriteLine(FieldText);
                break;
            }

            findObject.Replacement.ClearFormatting();
            findObject.Replacement.Text = FieldValue;
            object replace = Word.WdReplace.wdReplaceAll;

            findObject.Execute(ref OMissing, ref OMissing, ref OMissing, ref OMissing, ref OMissing,
                               ref OMissing, ref OMissing, ref OMissing, ref OMissing, ref OMissing,
                               ref replace, ref OMissing, ref OMissing, ref OMissing, ref OMissing);
        }