コード例 #1
0
        /// <summary>
        /// Return the content control containing the cursor, or
        /// null if we are outside a content control or the selection
        /// spans the content control boundary
        /// </summary>
        /// <param name="docx"></param>
        /// <param name="selection"></param>
        /// <returns></returns>
        public static Word.ContentControl getActiveContentControl(Word.Document docx, Word.Selection selection)
        {
            //Word.Selection selection = Globals.ThisAddIn.Application.Selection;

            // Word.ContentControls ccs = selection.ContentControls;
            // only has a value if the selection contains one or both *ends* of a ContentControl

            // so how do you expand a selection to include the entire content control?
            // or can we ask whether a content control is active,
            // ie the selection is in it?

            // or iterate through the content controls in the active doc,
            // asking whether their range contains my range? YES
            // Hmmm... what about nesting of cc?

            Word.ContentControl result = null;

            foreach (Word.ContentControl ctrl in docx.ContentControls)
            {
                int highestCount = -1;
                if (selection.InRange(ctrl.Range))
                {
                    //diagnostics("DEBUG - Got control");
                    log.Debug("In control: " + ctrl.ID);
                    int parents = countParent(ctrl);
                    if (parents > highestCount)
                    {
                        log.Debug(".. highest ");
                        result       = ctrl;
                        highestCount = parents;
                    }
                }
                // else user's selection is totally outside the content control, or crosses its boundary
            }
            //if (stateDocx.InControl == true)

            return(result);
        }