使用VSPackage基于行号突出显示visual studio的代码窗口

时间:2013-03-18 11:36:18

标签: visual-studio-2010 visual-studio c#-4.0 vspackage visual-studio-sdk

我正在构建一个VSpackage扩展来创建“VisualStudio工具窗口”。 我在工具窗口内有一个网格,由数字组成。如果用户选择网格的特定行。应强调该特定代码行。

更清楚, 假设我的网格包含:

第1 - 10行, 第2 - 15行, 第3-14行,

如果用户选择第1行,则应突出显示代码窗口中的第10行。 使用VisualStudio包是否可以使用此功能。我强烈认为这是可能的。因为大多数搜索结果都是这样的。

非常感谢任何帮助!!

2 个答案:

答案 0 :(得分:0)

我终于找到了基于google搜索的帖子的答案。希望这对其他人有帮助。

您需要使用“TextSelection”类来突出显示上面的代码行。

        foreach (CodeElement codeElement in projectItem.FileCodeModel.CodeElements)// search for the function to be opened
        {
            // get the namespace elements
            if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
            {
                foreach (CodeElement namespaceElement in codeElement.Children)
                {
                    // get the class elements
                    if (namespaceElement.Kind == vsCMElement.vsCMElementClass || namespaceElement.Kind == vsCMElement.vsCMElementInterface)
                    {
                        foreach (CodeElement classElement in namespaceElement.Children)
                        {
                            try
                            {
                                // get the function elements to highlight methods in code window
                                if (classElement.Kind == vsCMElement.vsCMElementFunction)
                                {
                                    if (!string.IsNullOrEmpty(highlightString))
                                    {
                                        if (classElement.Name.Equals(highlightString, StringComparison.Ordinal))
                                        {
                                            classElement.StartPoint.TryToShow(vsPaneShowHow.vsPaneShowTop, null);

                        classElement.StartPoint.TryToShow(vsPaneShowHow.vsPaneShowTop, null);

                            // get the text of the document
                         EnvDTE.TextSelection textSelection = window.Document.Selection as EnvDTE.TextSelection;

                            // now set the cursor to the beginning of the function
                            textSelection.MoveToPoint(classElement.StartPoint);
                            textSelection.SelectLine();

                                        }
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
        }

答案 1 :(得分:0)

您也可以使用更简单的解决方案;见下文

  int lineNo = 3;
  if (!isProjectItemOpen)
  {
       Window win = projectItem.Open();
       win.Visible = true;
       Document doc = win.Document;
       doc.Activate();
       var ts = dte.ActiveDocument.Selection;
       ts.GotoLine(lineNo, true);
  }