使用Visual Studio扩展设置光标位置

9

我正在编写一个Visual Studio 2010扩展程序,以帮助我浏览一个相当大的解决方案。
我已经有了一个基于对话框的VS扩展程序,根据一些搜索条件显示类名和函数名。现在我可以点击这个类/方法,然后就能打开正确的文件并跳转到函数。
现在我想要做的是将光标设置在该函数的开头。
我的跳转到函数的代码是:

Solution currentSolution = ((EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0")).Solution;
ProjectItem requestedItem = GetRequestedProjectItemToOpen(currentSolution.Projects, "fileToBeOpened");
if (requestedItem != null)
{
    // open the document
    Window window = requestedItem.Open(Constants.vsViewKindCode);
    window.Activate();

    // search for the function to be opened
    foreach (CodeElement codeElement in requestedItem.FileCodeModel.CodeElements)
    {
        // get the namespace elements
        if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
        {
            foreach (CodeElement namespaceElement in codeElement.Children)
            {
                // get the class elements
                if (namespaceElement.Kind == vsCMElement.vsCMElementClass)
                {
                   foreach (CodeElement classElement in namespaceElement.Children)
                   {
                       try
                       {
                           // get the function elements
                           if (classElement.Kind == vsCMElement.vsCMElementFunction)
                           {
                               if (classElement.Name.Equals("functionToBeOpened", StringComparison.Ordinal))
                               {
                                   classElement.StartPoint.TryToShow(vsPaneShowHow.vsPaneShowTop, null);
                                   this.Close();
                               }
                           }
                       }
                       catch
                       {
                       }
                   }
               }
           }
       }
   }
}

这里的重点是使用window.Activate();打开正确的文件和classElement.StartPoint.TryToShow(vsPaneShowHow.vsPaneShowTop, null);跳转到正确的函数。
不幸的是,光标没有设置到所请求的函数的开头。我该如何做?我想到的是类似classElement.StartPoint.SetCursor()的东西。
祝好 Simon


圈复杂度高?另外,看起来当你找到想要的东西时,你没有跳出该方法,这可能会产生一些副作用(猜测)。 - user1228
@Will:是的,我知道。这只是某种原型代码。仅用于演示如何打开所请求的类和函数... - Simon Linder
1个回答

16

我终于明白了...
你只需要使用TextSelection接口,并使用其中的方法MoveToPoint
因此,上面的代码现在是:

// open the file in a VS code window and activate the pane
Window window = requestedItem.Open(Constants.vsViewKindCode);
window.Activate();

// get the function element and show it
CodeElement function = CodeElementSearcher.GetFunction(requestedItem, myFunctionName);

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接