예제 #1
0
        public void WriteToRange(Word.Range fullRange)
        {
            Word.Range rangeCursor = fullRange;
            rangeCursor.Collapse(Word.WdCollapseDirection.wdCollapseStart);

            foreach (ContentItem item in Contents)
            {
                switch (item.Type)
                {
                case ContentType.Field:
                    Word.Field field = fullRange.Fields.Add(rangeCursor);
                    field.Code.Text = item.Text;
                    field.Code.Font = item.Font;

                    rangeCursor = field.Result;
                    rangeCursor.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
                    break;

                case ContentType.RangeText:
                    rangeCursor.Text = item.Text;
                    rangeCursor.Font = item.Font;

                    rangeCursor.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
                    break;

                case ContentType.LineBreak:
                    rangeCursor.InsertBreak(Word.WdBreakType.wdLineBreak);

                    rangeCursor.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
                    break;
                }
            }
        }
예제 #2
0
 /// <summary>
 /// 新起一段
 /// </summary>
 /// <param name="range">Range对象,可以为选区范围或者光标插入点</param>
 /// <param name="PrphStyle">新起一段的段落样式</param>
 /// <remarks></remarks>
 private void NewLine(Word.Range range, string PrphStyle)
 {
     Word.Range with_1 = range;
     with_1.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
     with_1.InsertParagraphAfter();
     with_1.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
     with_1.ParagraphFormat.set_Style(PrphStyle);
 }
예제 #3
0
        private void AddControl(Word.Range P_Range, object P_Range_O)
        {
            #region 新增語文成績文字框
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range;
            P_Range.Text = "語文成績:";
            P_Range.Collapse(ref P_Range_O);
            G_Txt_Chinese = this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_Chinese");
            #endregion

            #region 新增數學成績文字框
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range; //新增段落
            P_Range      = this.Paragraphs[Paragraphs.Count].Range;  //得到最後一個段落
            P_Range.Text = "數學成績:";                                  //新增文字內容
            P_Range.Collapse(ref P_Range_O);                         //折疊Range
            G_Txt_Math =                                             //新增控制元件
                         this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_Math");
            #endregion

            #region 新增英語成績文字框
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range; //新增段落
            P_Range      = this.Paragraphs[Paragraphs.Count].Range;  //得到最後一個段落
            P_Range.Text = "英語成績:";                                  //新增文字內容
            P_Range.Collapse(ref P_Range_O);                         //折疊Range
            G_Txt_English =                                          //新增控制元件
                            this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_English");
            #endregion

            #region 新增按鈕
            P_Range = this.Paragraphs.Add(ref G_Missing).Range; //新增段落
            P_Range = this.Paragraphs[Paragraphs.Count].Range;  //得到最後一個段落
            Button P_Btn_OK =                                   //新增按鈕控制元件
                              this.Controls.AddButton(P_Range, 100, 20, "P_Btn_OK");
            P_Btn_OK.Click +=                                   //為按鈕新增事件
                              new EventHandler(P_Btn_OK_Click);
            P_Btn_OK.Text = "新增";                               //設定按鈕文字內容
            #endregion

            #region 新增文字內容
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range; //新增段落
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range; //新增段落
            P_Range      = this.Paragraphs[Paragraphs.Count].Range;  //得到最後一個段落
            P_Range.Text = "顯示資料:";                                  //顯示文字訊息
            #endregion

            #region 新增DataGridView控制元件
            P_Range    = this.Paragraphs.Add(ref G_Missing).Range; //新增新段落
            P_Range    = this.Paragraphs[Paragraphs.Count].Range;  //得到最後一個段落
            G_Dgv_Data =                                           //新增控制元件
                         this.Controls.AddDataGridView(P_Range, 400, 200, "P_Dgv");
            G_Dgv_Data.DataSource = G_List_Student;                //將資料繫結到DataGridView控制元件
            #endregion
        }
        private void AddControl(Word.Range P_Range, object P_Range_O)
        {
            #region 添加语文成绩文本框
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range;
            P_Range.Text = "语文成绩:";
            P_Range.Collapse(ref P_Range_O);
            G_Txt_Chinese = this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_Chinese");
            #endregion

            #region 添加数学成绩文本框
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range; //添加段落
            P_Range      = this.Paragraphs[Paragraphs.Count].Range;  //得到最后一个段落
            P_Range.Text = "数学成绩:";                                  //添加文本内容
            P_Range.Collapse(ref P_Range_O);                         //折叠Range
            G_Txt_Math =                                             //添加控件
                         this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_Math");
            #endregion

            #region 添加英语成绩文本框
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range; //添加段落
            P_Range      = this.Paragraphs[Paragraphs.Count].Range;  //得到最后一个段落
            P_Range.Text = "英语成绩:";                                  //添加文本内容
            P_Range.Collapse(ref P_Range_O);                         //折叠Range
            G_Txt_English =                                          //添加控件
                            this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_English");
            #endregion

            #region 添加按钮
            P_Range = this.Paragraphs.Add(ref G_Missing).Range; //添加段落
            P_Range = this.Paragraphs[Paragraphs.Count].Range;  //得到最后一个段落
            Button P_Btn_OK =                                   //添加按钮控件
                              this.Controls.AddButton(P_Range, 100, 20, "P_Btn_OK");
            P_Btn_OK.Click +=                                   //为按钮添加事件
                              new EventHandler(P_Btn_OK_Click);
            P_Btn_OK.Text = "添加";                               //设置按钮文本内容
            #endregion

            #region 添加文本内容
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range; //添加段落
            P_Range      = this.Paragraphs.Add(ref G_Missing).Range; //添加段落
            P_Range      = this.Paragraphs[Paragraphs.Count].Range;  //得到最后一个段落
            P_Range.Text = "显示数据:";                                  //显示文本信息
            #endregion

            #region 添加DataGridView控件
            P_Range    = this.Paragraphs.Add(ref G_Missing).Range; //添加新段落
            P_Range    = this.Paragraphs[Paragraphs.Count].Range;  //得到最后一个段落
            G_Dgv_Data =                                           //添加控件
                         this.Controls.AddDataGridView(P_Range, 400, 200, "P_Dgv");
            G_Dgv_Data.DataSource = G_List_Student;                //将数据绑定到DataGridView控件
            #endregion
        }
예제 #5
0
 /// <summary>
 /// Finds the next redaction mark in the document.
 /// </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>
 /// <param name="CurrentView">The current view type.</param>
 /// <param name="WrapAtEnd">True to prompt to wrap around at the end, otherwise False.</param>
 /// <returns>True if a mark was found, otherwise False.</returns>
 private bool FindNextMark(ref Word.Range CurrentRange, Word.WdViewType CurrentView, bool WrapAtEnd)
 {
     if (FindNextMarkInCurrentStory(ref CurrentRange) || FindNextMarkInOtherStory(ref CurrentRange))
     {
         //extend it out and select it
         ExtendNextMark(ref CurrentRange, false);
         CurrentRange.Select();
         return(true);
     }
     else
     {
         if (WrapAtEnd)
         {
             if (GenericMessageBox.Show(Resources.SearchFromBeginning, Resources.AppName, MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0) == DialogResult.OK)
             {
                 //move the range to the start of the document and search again
                 CurrentRange = CurrentRange.Document.StoryRanges[Word.WdStoryType.wdMainTextStory];
                 CurrentRange.Collapse(ref CollapseStart);
                 return(FindNextMark(ref CurrentRange, CurrentView, false));
             }
             else
             {
                 return(false);
             }
         }
         else
         {
             GenericMessageBox.Show(Resources.NoRedactionMarks, Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);
             return(false);
         }
     }
 }
예제 #6
0
        /// <summary>
        /// Finds the next redaction mark in subsequent document stories.
        /// </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 bool FindNextMarkInOtherStory(ref Word.Range CurrentRange)
        {
            //move forward a story
            int NextStory = (int)CurrentRange.StoryType + 1;

            while (NextStory <= 17)
            {
                try
                {
                    CurrentRange = CurrentRange.Document.StoryRanges[(Word.WdStoryType)NextStory];
                    CurrentRange.Collapse(ref CollapseStart);

                    if (FindNextMarkInCurrentStory(ref CurrentRange))
                    {
                        if (RedactCommon.IsHeaderFooter((Word.WdStoryType)NextStory))
                        {
                            MoveHeaderFooterFocus(CurrentRange, RedactCommon.FindSectionWithHeaderFooter(CurrentRange.Document, CurrentRange), RedactCommon.GetHeaderFooterType((Word.WdStoryType)NextStory));
                        }
                        return(true);
                    }
                }
                catch (COMException)
                { }

                NextStory++;
            }

            return(false);
        }
예제 #7
0
        /// <summary>
        /// Finds the previous redaction mark in previous document stories of the current type (e.g. previous headers).
        /// </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 FindPreviousMarkInStoryRanges(ref Word.Range CurrentRange)
        {
            object CollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;

            Word.WdHeaderFooterIndex?headerFooterId = null;

            Word.Range PreviousStoryRange = RedactCommon.PreviousStoryRange(CurrentRange);
            while (PreviousStoryRange != null)
            {
                //if we're in headers/footers, we need to get our location so we can update the current view
                if (CurrentRange.StoryType != Word.WdStoryType.wdTextFrameStory)
                {
                    headerFooterId = RedactCommon.GetHeaderFooterType(CurrentRange.StoryType);
                }

                CurrentRange       = PreviousStoryRange;
                PreviousStoryRange = RedactCommon.PreviousStoryRange(CurrentRange);
                CurrentRange.Collapse(ref CollapseEnd);
                if (FindPreviousMarkInCurrentStoryRange(ref CurrentRange))
                {
                    //move the focus in the view
                    if (RedactCommon.IsHeaderFooter(CurrentRange.StoryType))
                    {
                        MoveHeaderFooterFocus(CurrentRange, RedactCommon.FindSectionWithHeaderFooter(CurrentRange.Document, CurrentRange), headerFooterId);
                    }
                    return(true);
                }
            }
            return(false);
        }
예제 #8
0
        public void AddControl(string key)
        {
            ServicesProfile profile = Wkl.MainCtrl.ServiceCtrl.GetProfile(key);

            PdmServiceProfile pdmProfile = profile.PdmProfile;

            profile.ContentService.MarkProntDoc = true;

            Word.Range rangeToInsert = Wkl.MainCtrl.CommonCtrl.CommonProfile.CurrentSelection.Range;
            rangeToInsert.Collapse(Word.WdCollapseDirection.wdCollapseEnd);

            try
            {
                ControlBase control = Add(pdmProfile.ControlType, rangeToInsert);

                pdmProfile.Control = control;

                ControlEventBinding(key);

                MarkProntoDoc(key);
            }
            catch (Exception ex)
            {
                profile.Error   = ex;
                profile.Message = ex.Message;
            }
        }
예제 #9
0
        /// <summary>
        /// Finds the previous redaction mark in the document.
        /// </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>
        /// <param name="CurrentView">The current view type.</param>
        /// <param name="WrapAtStart">True to prompt to wrap around at the start, otherwise False.</param>
        /// <returns>True if a mark was found, otherwise False.</returns>
        private bool FindPreviousMark(ref Word.Range CurrentRange, Word.WdViewType CurrentView, bool WrapAtStart)
        {
            if (FindPreviousMarkInCurrentStory(ref CurrentRange) || FindPreviousMarkInOtherStory(ref CurrentRange))
            {
                //extend it out and select it
                ExtendPreviousMark(ref CurrentRange, false);
                CurrentRange.Select();
                return(true);
            }
            else
            {
                if (WrapAtStart)
                {
                    if (GenericMessageBox.Show(Resources.SearchFromEnd, Resources.AppName, MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0) == DialogResult.OK)
                    {
                        //they want to wrap around, so find the last story and start again
                        CurrentRange = GetLastStory(ref CurrentRange);
                        CurrentRange.Collapse(ref CollapseEnd);

                        return(FindPreviousMark(ref CurrentRange, CurrentView, false));
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    GenericMessageBox.Show(Resources.NoRedactionMarks, Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);
                    return(false);
                }
            }
        }
예제 #10
0
        /// <summary>
        /// Finds the next redaction mark in subsequent document stories of the current type (e.g. subsequent headers).
        /// </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 FindNextMarkInStoryRanges(ref Word.Range SelectionRange)
        {
            object CollapseStart = Word.WdCollapseDirection.wdCollapseStart;

            Word.WdHeaderFooterIndex?headerFooterId = null;

            while (SelectionRange.NextStoryRange != null)
            {
                //get the header/footer ID
                if (SelectionRange.StoryType != Word.WdStoryType.wdTextFrameStory)
                {
                    headerFooterId = RedactCommon.GetHeaderFooterType(SelectionRange.StoryType);
                }

                SelectionRange = SelectionRange.NextStoryRange;
                SelectionRange.Collapse(ref CollapseStart);
                if (FindNextMarkInCurrentStoryRange(ref SelectionRange))
                {
                    //move the focus in the view
                    if (RedactCommon.IsHeaderFooter(SelectionRange.StoryType))
                    {
                        MoveHeaderFooterFocus(SelectionRange, RedactCommon.FindSectionWithHeaderFooter(SelectionRange.Document, SelectionRange), headerFooterId);
                    }
                    return(true);
                }
            }
            return(false);
        }
예제 #11
0
        // -----------

        private void MoveCursorToBeginningOfDocument()
        {
            Word.Range rng = wordApp.ActiveDocument.Paragraphs[1].Range;

            rng.Collapse(Word.WdCollapseDirection.wdCollapseStart);

            rng.Select();
        }
예제 #12
0
        /// <summary> 代码向前缩进 </summary>
        public void Button_AddSpace_Click(object sender, RibbonControlEventArgs e)
        {
            // 要删除或者添加的字符数
            string InsertSpace = "";

            try
            {
                UInt16 SpaceCount = 0;
                SpaceCount = Convert.ToUInt16(this.EditBox_SpaceCount.Text);
                StringBuilder sb = new StringBuilder(4);
                for (var i = 1; i <= SpaceCount; i++)
                {
                    sb.Append(" ");
                }
                InsertSpace = sb.ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("请先设置要添加或者删除的字符数");
                return;
            }
            //
            try
            {
                _app.ScreenUpdating = false;
                int   StartIndex = 0;
                int   EndIndex   = 0;
                Range rg         = _app.Selection.Range;
                StartIndex = rg.Start;
                Range  rgPara = default(Range); //每一段的起始位置
                var    c      = rg.Paragraphs.Count;
                string txt    = "";             // 每一段的文本
                foreach (Paragraph para in rg.Paragraphs)
                {
                    txt = para.Range.Text;
                    if (txt != '\r' + "\a")
                    {
                        // 对于一个表格而言,在每一个表格的末尾,都有一个表示结尾的段落。此段落中有两个字符,所对应的ASCII码分别为13和7。
                        rgPara = para.Range;
                        rgPara.Collapse(Direction: WdCollapseDirection.wdCollapseStart);
                        // 如果Start或End只指定一个的话,那么另一个并不会与指定了的那一个相同的。    rgPara = Doc.Range(para.Range.Start)
                        rgPara.InsertAfter(InsertSpace);
                    }
                    EndIndex = para.Range.End;
                }

                _activeDoc.Range(StartIndex, EndIndex).Select();
            }
            catch (Exception)
            {
                //  MessageBox.Show("代码缩进出错!" & vbCrLf &
                //             ex.Message & vbCrLf & ex.TargetSite.Name, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error)
            }
            finally
            {
                _app.ScreenUpdating = true;
            }
        }
예제 #13
0
        void DirtyTheDoc()
        {
            Word.Range rng           = Globals.ThisAddIn.Application.ActiveDocument.Content;
            object     collapseStart = Word.WdCollapseDirection.wdCollapseStart;

            rng.Collapse(ref collapseStart);
            rng.Text = " ";
            rng.Delete();
        }
예제 #14
0
        /// <summary> 代码向前缩进 </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Button_DeleteSapce_Click(object sender, RibbonControlEventArgs e)
        {
            // 要删除或者添加的字符数
            int    SpaceCount  = 0;
            string InsertSpace = "";

            try
            {
                SpaceCount = Convert.ToUInt16(this.EditBox_SpaceCount.Text);
                StringBuilder sb = new StringBuilder(4);
                for (var i = 1; i <= SpaceCount; i++)
                {
                    sb.Append(" ");
                }
                InsertSpace = sb.ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("请先设置要添加或者删除的字符数");
                return;
            }
            //
            try
            {
                _app.ScreenUpdating = false;
                int   StartIndex = 0;
                int   EndIndex   = 0;
                Range rg         = _app.Selection.Range;
                StartIndex = rg.Start;
                string str    = "";
                Range  rgPara = default(Range); //每一段的起始位置
                foreach (Paragraph para in rg.Paragraphs)
                {
                    str = para.Range.Text;
                    if (str.Length > SpaceCount && str.Substring(0, SpaceCount) == InsertSpace)
                    {
                        rgPara = para.Range;
                        rgPara.Collapse(Direction: WdCollapseDirection.wdCollapseStart);
                        rgPara.Delete(Unit: WdUnits.wdCharacter, Count: SpaceCount);
                    }
                    EndIndex = para.Range.End;
                }
                _activeDoc.Range(StartIndex, EndIndex).Select();
            }
            catch (Exception)
            {
                //  MessageBox.Show("代码缩进出错!" & vbCrLf &
                //                   ex.Message & vbCrLf & ex.TargetSite.Name, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error)
            }
            finally
            {
                _app.ScreenUpdating = true;
            }
        }
        private Word.Range FindNextOpen(Word.Range range, string text)
        {
            Word.Find  find   = this.CreateFind(range, text);
            Word.Range result = range.Duplicate;

            if (!find.Found)
            {
                // Make sure that the next closing field will be found first.
                result.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
            }

            return(result);
        }
예제 #16
0
        /// <summary>
        /// Find and mark all instances of a string in a specific StoryRange.
        /// </summary>
        /// <param name="StoryRange">A Range specifying the story range to search.</param>
        /// <returns>True if a hit was found, False otherwise.</returns>
        private int FindAndMarkInStory(Word.Range StoryRange)
        {
            object    CollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
            RangeData LastHit     = new RangeData();
            int       HitCount    = 0;
            object    Missing     = Type.Missing;
            object    FindText    = textBox.Text;

            //text boxes in headers/footers aren't in the text box story
            if ((int)StoryRange.StoryType > 5 && StoryRange.ShapeRange.Count > 0)
            {
                foreach (Word.Shape Shape in StoryRange.ShapeRange)
                {
                    Word.Range ShapeRange = RedactCommon.RangeFromShape(Shape);
                    if (ShapeRange != null)
                    {
                        HitCount += FindAndMarkInStory(ShapeRange);
                    }
                }
            }

            Word.Find FindScope = StoryRange.Find;

            //set search options
            FindScope.IgnorePunct       = checkBoxIgnorePunct.Checked;
            FindScope.IgnoreSpace       = checkBoxIgnoreWhitespace.Checked;
            FindScope.MatchAllWordForms = checkBoxWordForms.Checked;
            FindScope.MatchCase         = checkBoxMatchCase.Checked;
            FindScope.MatchPrefix       = checkBoxMatchPrefix.Checked;
            FindScope.MatchSoundsLike   = checkBoxSoundsLike.Checked;
            FindScope.MatchSuffix       = checkBoxMatchSuffix.Checked;
            FindScope.MatchWholeWord    = checkBoxWholeWord.Checked;
            FindScope.MatchWildcards    = checkBoxWildcards.Checked;

            while (FindScope.Execute(ref FindText, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing) && (StoryRange.Start != LastHit.Start || StoryRange.End != LastHit.End))
            {
                HitCount++;
                LastHit = new RangeData(StoryRange.Start, StoryRange.End);
                StoryRange.Font.Shading.BackgroundPatternColor = (Word.WdColor)ShadingColor;
                StoryRange.Collapse(ref CollapseEnd);
            }

            //check in any subsequent stories
            if (StoryRange.NextStoryRange != null)
            {
                HitCount += FindAndMarkInStory(StoryRange.NextStoryRange);
            }

            return(HitCount);
        }
예제 #17
0
        private List <string> G_Str_Files = new List <string>(); //定义字符串集合

        private void btn_split_Click(object sender, EventArgs e)
        {
            btn_Merge.Enabled = false;                                  //停用合并按钮
            ThreadPool.QueueUserWorkItem(                               //开始线程池
                (pp) =>                                                 //使用lambda表达式
            {
                G_wa = new Microsoft.Office.Interop.Word.Application(); //创建应用程序对象
                Word.Document P_MainDocument =                          //新建合并文档对象
                                               G_wa.Documents.Add(ref G_missing, ref G_missing
                                                                  , ref G_missing, ref G_missing);
                foreach (string P_Str in G_Str_Files)               //遍历文档的集合
                {
                    object P_strs            = P_Str;               //创建object对象
                    Word.Document P_Document = G_wa.Documents.Open( //打开Word文档
                        ref P_strs, 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 o);
                    Word.Range P_Range_temp =                                        //得到文档全部范围
                                              P_Document.Range(ref G_missing, ref G_missing);
                    P_Range_temp.Select();                                           //选择文档全部范围
                    P_Range_temp.Copy();                                             //复制文档全部范围
                    Word.Range P_Range_temp2 =                                       //得到文档的范围
                                               P_MainDocument.Range(ref G_missing, ref G_missing);
                    object P_end = Word.WdCollapseDirection.wdCollapseEnd;           //创建object对象
                    P_Range_temp2.Collapse(ref P_end);                               //折叠文档范围
                    P_Range_temp2.Select();                                          //选择档的最后位置
                    P_Range_temp2.Paste();                                           //粘贴文档内容
                    ((Word._Document)P_Document).Close(ref G_missing, ref G_missing, //关闭文档
                                                       ref G_missing);
                }
                object P_SavePath = G_SaveFileDialog.FileName; //创建object对象
                P_MainDocument.SaveAs(                         //保存合并后的文档
                    ref P_SavePath, 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._Application)G_wa.Application).Quit( //退出应用程序
                    ref G_missing, ref G_missing, ref G_missing);
                this.Invoke(                                //调用窗体线程
                    (MethodInvoker)(() =>                   //使用lambda表达式
                {
                    Clipboard.Clear();                      //清空剪切板
                    MessageBox.Show(                        //提示已经创建Word
                        "成功合并Word文档!", "提示!");
                    btn_Merge.Enabled = true;               //启用合并按钮
                }));
            });
        }
예제 #18
0
        private List <string> G_Str_Files = new List <string>(); //定義字串集合

        private void btn_split_Click(object sender, EventArgs e)
        {
            btn_Merge.Enabled = false;                                  //停用合併按鈕
            ThreadPool.QueueUserWorkItem(                               //開始線程池
                (pp) =>                                                 //使用lambda表達式
            {
                G_wa = new Microsoft.Office.Interop.Word.Application(); //建立應用程式物件
                Word.Document P_MainDocument =                          //新建合併文件檔物件
                                               G_wa.Documents.Add(ref G_missing, ref G_missing
                                                                  , ref G_missing, ref G_missing);
                foreach (string P_Str in G_Str_Files)               //深度搜尋文件檔的集合
                {
                    object P_strs            = P_Str;               //建立object物件
                    Word.Document P_Document = G_wa.Documents.Open( //打開Word文件檔
                        ref P_strs, 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_temp =                                        //得到文件檔全部範圍
                                              P_Document.Range(ref G_missing, ref G_missing);
                    P_Range_temp.Select();                                           //選擇文件檔全部範圍
                    P_Range_temp.Copy();                                             //複製文件檔全部範圍
                    Word.Range P_Range_temp2 =                                       //得到文件檔的範圍
                                               P_MainDocument.Range(ref G_missing, ref G_missing);
                    object P_end = Word.WdCollapseDirection.wdCollapseEnd;           //建立object物件
                    P_Range_temp2.Collapse(ref P_end);                               //折疊文件檔範圍
                    P_Range_temp2.Select();                                          //選擇檔的最後位置
                    P_Range_temp2.Paste();                                           //貼上文件檔內容
                    ((Word._Document)P_Document).Close(ref G_missing, ref G_missing, //關閉文件檔
                                                       ref G_missing);
                }
                object P_SavePath = G_SaveFileDialog.FileName; //建立object物件
                P_MainDocument.SaveAs(                         //儲存合併後的文件檔
                    ref P_SavePath, 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._Application)G_wa.Application).Quit( //退出應用程式
                    ref G_missing, ref G_missing, ref G_missing);
                this.Invoke(                                //呼叫視窗線程
                    (MethodInvoker)(() =>                   //使用lambda表達式
                {
                    Clipboard.Clear();                      //清空剪下板
                    MessageBox.Show(                        //提示已經建立Word
                        "成功合併Word文件檔!", "提示!");
                    btn_Merge.Enabled = true;               //啟用合併按鈕
                }));
            });
        }
예제 #19
0
        private void button1_Click(object sender, EventArgs e)
        {
            Word.Application MyWord = new Word.Application();
            Word.Document    MyDoc  = MyWord.Documents.Open(DefaultPath + @"\ReadAndReplaceBulletListFromWord\test.docx");
            MyWord.Visible = true;
            Word.Range rngTmp = MyDoc.Range(0, 0);

            //將項目符號取代成指定符號
            foreach (Word.Paragraph p in MyWord.ActiveDocument.Paragraphs)
            {
                if (p.Range.ListFormat.ListType != Word.WdListType.wdListBullet)
                {
                    continue;
                }

                //移除項目符號
                p.Range.ListFormat.ApplyBulletDefault(DefaultListBehavior: Word.WdDefaultListBehavior.wdWord9ListBehavior);

                p.Range.Select();
                MyWord.Selection.HomeKey(Word.WdUnits.wdLine, Word.WdMovementType.wdMove);
                rngTmp      = MyWord.Selection.Range;
                rngTmp.Text = "□";
            }

            //替換指定符號為核取方塊控制
            object strStart = "□";

            Word.Range MyRange = MyDoc.Content;
            MyRange.Find.Text    = "□";
            MyRange.Find.Forward = true;
            MyRange.Find.Execute(strStart);

            while (MyRange.Find.Found)
            {
                //選取游標取代
                rngTmp.SetRange(MyRange.Start, MyRange.End);
                rngTmp.Select();
                Word.ContentControl checkbox = rngTmp.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox);
                checkbox.SetCheckedSymbol(82, "Wingdings 2");

                //游標移至被加入的核取方塊後
                MyRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
                MyRange.Select();
                MyRange.Font.Size = 14;
                MyRange.Find.Execute(strStart);
            }

            MessageBox.Show("處理完成");
        }
        private DataGridView G_Dgv_Data;                              //定义DataGridView类型字段
        #endregion

        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            #region 添加姓名文本框
            Word.Range P_Range =                                       //得到文档区域
                                 this.ActiveWindow.Document.Range(ref G_Missing, ref G_Missing);
            P_Range.Text = "姓名:    ";                                  //添加文本内容
            object P_Range_O = Word.WdCollapseDirection.wdCollapseEnd; //创建折叠参数对象
            P_Range.Collapse(ref P_Range_O);                           //折叠Range
            G_Txt_Name =                                               //添加控件
                         this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_Name");
            #endregion
            #region 添加年龄文本框
            P_Range   = this.Paragraphs.Add(ref G_Missing).Range;         //添加段落
            P_Range   = this.Paragraphs.Add(ref G_Missing).Range;         //添加段落
            P_Range   = this.Paragraphs[this.Paragraphs.Count - 1].Range; //得到最后一个段落
            G_Txt_Age =                                                   //添加控件
                        this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_Age");
            P_Range = this.Paragraphs[this.Paragraphs.Count - 1].Range;   //得到最后一个段落
            object P_Range_O2 = Word.WdCollapseDirection.wdCollapseStart; //创建折叠参数对象
            P_Range.Collapse(ref P_Range_O2);                             //折叠Range
            P_Range.Text = "年龄:    ";                                     //添加文本
            #endregion
            AddControl(P_Range, P_Range_O);                               //向文档中添加控件
        }
예제 #21
0
        private DataGridView G_Dgv_Data;                              //定義DataGridView類型欄位
        #endregion

        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            #region 新增姓名文字框
            Word.Range P_Range =                                       //得到文檔區域
                                 this.ActiveWindow.Document.Range(ref G_Missing, ref G_Missing);
            P_Range.Text = "姓名:    ";                                  //新增文字內容
            object P_Range_O = Word.WdCollapseDirection.wdCollapseEnd; //建立折疊參數對像
            P_Range.Collapse(ref P_Range_O);                           //折疊Range
            G_Txt_Name =                                               //新增控制元件
                         this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_Name");
            #endregion
            #region 新增年齡文字框
            P_Range   = this.Paragraphs.Add(ref G_Missing).Range;         //新增段落
            P_Range   = this.Paragraphs.Add(ref G_Missing).Range;         //新增段落
            P_Range   = this.Paragraphs[this.Paragraphs.Count - 1].Range; //得到最後一個段落
            G_Txt_Age =                                                   //新增控制元件
                        this.Controls.AddTextBox(P_Range, 100, 20, "P_Txt_Age");
            P_Range = this.Paragraphs[this.Paragraphs.Count - 1].Range;   //得到最後一個段落
            object P_Range_O2 = Word.WdCollapseDirection.wdCollapseStart; //建立折疊參數對像
            P_Range.Collapse(ref P_Range_O2);                             //折疊Range
            P_Range.Text = "年齡:    ";                                     //新增文字
            #endregion
            AddControl(P_Range, P_Range_O);                               //向文檔中新增控制元件
        }
예제 #22
0
        //---------------------------------------------------------------------
        private void Test10()
        {
            //<Snippet45>
            //<Snippet46>
            Word.Range rng = this.Paragraphs[1].Range;
            //</Snippet46>

            //<Snippet47>
            rng.Collapse(Word.WdCollapseDirection.wdCollapseStart);
            //</Snippet47>

            //<Snippet48>
            rng.Text = " New Text ";
            //</Snippet48>
            //<Snippet49>
            rng.Select();
            //</Snippet49>
            //</Snippet45>


            //<Snippet50>
            rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
            //</Snippet50>
        }
예제 #23
0
        /// <summary>
        /// Добавляет в конец файла docx изображение.
        /// Изображение временно добавляется в папку Images наследника директории исполняемого файла.
        /// </summary>
        /// <param name="img">Изображение.</param>
        public void AddImage(Bitmap img)
        {
            string pathImg      = @"Images\tmp.png";
            string absolutePath = Path.Combine(AppFile.DirectoryName, pathImg);

            img.Save(absolutePath);

            // Перемещение курсора в конец файла
            Word.Range Range = Docx.Range(0, Docx.Content.End);
            object     dir   = Word.WdCollapseDirection.wdCollapseEnd;

            Range.Collapse(ref dir);
            Range.Select();
            // Вставка рисунка
            Docx.Application.Selection.InlineShapes.AddPicture(absolutePath);
        }
예제 #24
0
파일: Word.cs 프로젝트: Zagii/EAkzg
        public void wstawTekst(object bookmark, String tekst, String styl = "HLD_normalny")
        {
            //   Wordy.Range r = doc.Range(ref koniecDok);
            wstawTytulRozdzialu(bookmark, tekst, "HLD_normalny");
            return;

            Wordy.Bookmark book = doc.Bookmarks.get_Item(ref bookmark);

            Wordy.Paragraph par = doc.Paragraphs.Add();
            Wordy.Range     r   = par.Range;
            r.Collapse();
            r.Text    = tekst + "\n";
            koniecDok = r.End;

            object indentStyle = styl;

            r.set_Style(indentStyle);
        }
예제 #25
0
        /// <summary>
        /// Selects the next mark (relative to the current selection).
        /// </summary>
        private void SelectNextMark()
        {
            Application.ScreenUpdating = false;
            Word.WdViewType OriginalView = Application.ActiveWindow.View.Type;

            Word.Selection CurrentSelection  = Application.Selection;
            Word.Range     OriginalSelection = CurrentSelection.Range.Duplicate;

            //collapse to the end of the current selection
            Word.Range SelectionRange = CurrentSelection.Range;
            SelectionRange.Collapse(ref CollapseEnd);
            ExtendNextMark(ref SelectionRange, true);

            if (!FindNextMark(ref SelectionRange, OriginalView, (CurrentSelection.StoryType != Word.WdStoryType.wdMainTextStory || CurrentSelection.End != 0) /* don't wrap from cp0 */))
            {
                OriginalSelection.Select();
            }

            Application.ScreenUpdating = true;
        }
예제 #26
0
파일: ThisDocument.cs 프로젝트: fberga/Iren
 public void FormatTextOverDimension(Microsoft.Office.Tools.Word.RichTextContentControl ctrl, int length, bool overDimension)
 {
     if (overDimension)
     {
         string     text = ctrl.Text;
         Word.Range rng  = ctrl.Range;
         rng.Text            = text.Substring(0, length);
         rng.Font.ColorIndex = WdColorIndex.wdBlack;
         rng.Collapse(WdCollapseDirection.wdCollapseEnd);
         rng.Text            = text.Substring(length, text.Length - length);
         rng.Font.ColorIndex = WdColorIndex.wdRed;
     }
     else
     {
         if (!ctrl.ShowingPlaceholderText)
         {
             ctrl.Range.Font.ColorIndex = WdColorIndex.wdAuto;
         }
     }
 }
예제 #27
0
        /// <summary>
        /// Selects the previous mark (relative to the current selection).
        /// </summary>
        private void SelectPreviousMark()
        {
            Application.ScreenUpdating = false;
            Word.WdViewType OriginalView = Application.ActiveWindow.View.Type;

            Word.Selection CurrentSelection  = Application.Selection;
            Word.Range     OriginalSelection = CurrentSelection.Range.Duplicate;

            //collapse to the start of the current selection
            Word.Range SelectionRange = CurrentSelection.Range;
            SelectionRange.Collapse(ref CollapseStart);
            ExtendPreviousMark(ref SelectionRange, true);

            if (!FindPreviousMark(ref SelectionRange, OriginalView, (SelectionRange.StoryType != Word.WdStoryType.wdEndnoteSeparatorStory || SelectionRange.End < SelectionRange.Document.StoryRanges[Word.WdStoryType.wdEndnoteSeparatorStory].StoryLength - 1)))
            {
                OriginalSelection.Select();
            }

            Application.ScreenUpdating = true;
        }
예제 #28
0
파일: Word.cs 프로젝트: Zagii/EAkzg
        public void wstawSpisTresci(object bookmark)
        {
            //  return;
            Wordy.Range oRng = doc.Bookmarks.get_Item(ref bookmark).Range;
            oRng.Text = "";
            object oTrueValue  = true;
            object oFalseValue = false;

            oRng.Collapse();
            //   Wordy.Range rangeForTOC = doc.Range( oRng.Start, ref missing);

            /*spisTresci = doc.TablesOfContents.Add(oRng, ref oTrueValue, ref missing, ref missing,
             *            ref missing, ref missing, ref oTrueValue,
             *               ref oTrueValue, ref oTrueValue, ref oTrueValue,
             *               ref oTrueValue, ref oTrueValue);
             */
            spisTresci = doc.TablesOfContents.Add(oRng, ref oFalseValue, ref missing, ref missing,
                                                  ref missing, ref missing, ref oTrueValue,
                                                  ref oTrueValue, ref oTrueValue, ref oTrueValue,
                                                  ref oTrueValue, ref oTrueValue);

            object h1 = stylRozdz;
            object h2 = stylPodrozdz;
            object h3 = stylPodrozdz2;

            object h4 = stylPodrozdz3;

            /*       string txt="";
             * foreach (Wordy.HeadingStyle x in spisTresci.HeadingStyles)
             * {
             *     txt += x.ToString();
             * }*/


            spisTresci.HeadingStyles.Add(ref h1, 1);
            spisTresci.HeadingStyles.Add(ref h2, 2);
            //    spisTresci.HeadingStyles.Add(ref h3, 3);
            //    spisTresci.HeadingStyles.Add(ref h4, 4);
            spisTresci.LowerHeadingLevel = 2;
            spisTresci.Update();
        }
예제 #29
0
        // вставляем пустой абзац, доступ к его тексту и свойствам через
        public void InsertParagraphAfter()
        {
            if (Closed)
            {
                throw new Exception("Ошибка при обращении к документу Word. Документ уже закрыт.");
            }
            // сворачиваем текущую позицию и переходим в ее конец
            Object collapseDirection = Word.WdCollapseDirection.wdCollapseEnd;

            try
            {
                _currentRange.Collapse(ref collapseDirection);
                //вставляем абзац
                _currentRange.InsertParagraphAfter();
                _selection = new WordSelection(_currentRange);
            }
            catch (Exception wordError)
            {
                throw wordError;
            }
        }
예제 #30
0
        void WriteVsto(int size)
        {
            Stopwatch sw = Stopwatch.StartNew();

            _app.ScreenUpdating = false;

            Interop.WdColor[] colors =
            {
                Interop.WdColor.wdColorRed,
                Interop.WdColor.wdColorGreen,
                Interop.WdColor.wdColorBlue,
                Interop.WdColor.wdColorGold,
                Interop.WdColor.wdColorAqua,
                Interop.WdColor.wdColorPink,
                Interop.WdColor.wdColorDarkBlue
            };
            Interop.Document document = _app.ActiveDocument;
            for (int i = 1; i <= size; i++)
            {
                Interop.Paragraph paragraph = document.Range().Paragraphs.Add();
                for (int j = 1; j <= size; j++)
                {
                    Interop.Range range = paragraph.Range;
                    range.Collapse(Interop.WdCollapseDirection.wdCollapseEnd);
                    range.Text = " " + (1000 * i + j);
                    Interop.Font font = range.Font;
                    font.Fill.BackColor.RGB = GenerateRandomColor();
                    font.Color  = colors[_rand.Next(6)];
                    font.Size   = _rand.Next(9, 14);
                    font.Italic = -_rand.Next(2);
                    font.Bold   = -_rand.Next(2);
                }
            }

            _app.ScreenUpdating = true;

            sw.Stop();
            MessageBox.Show(sw.Elapsed.ToString(), $"VSTO: write {size * size}");
        }