You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取MSVC编辑器面板的首尾行号(C# VSIX扩展开发)

实现VSIX扩展跳转到编辑器垂直中心:获取面板首尾行号

在MSVC中,快捷键Ctrl+Up可将光标定位到文本编辑器面板的首行,Ctrl+Down可定位到面板末行。我们需要开发C# VSIX扩展,获取该面板的首尾行号,以此实现跳转到面板垂直中心的功能,现有基础代码如下:

private void JumpVCenter()
{
    // Clear our current selection when we jump.
    View.Selection.Clear();

    CaretPosition caretPos = View.Caret.Position;
    ITextBuffer buffer     = View.TextBuffer;
    ITextSnapshot snapshot = buffer.CurrentSnapshot;
    SnapshotPoint start    = caretPos.BufferPosition;

    // Code here to get the top/bottom line number of the pane.
    // ...
}

获取编辑器面板首尾行号的实现方案

要获取当前可见面板的首尾行号,需要利用IWpfTextView的视口属性,将视口坐标映射到文本快照位置,再转换为行号:

  • 通过View.ViewportTop和View.ViewportBottom获取视口的上下边界坐标
  • 使用View.TextViewLines.GetTextViewLineContainingYCoordinate()方法,将坐标转换为对应的文本行
  • 从文本行中提取快照位置,再转换为行号

完整实现代码

private void JumpVCenter()
{
    // 跳转时清除当前选中内容
    View.Selection.Clear();

    ITextSnapshot snapshot = View.TextBuffer.CurrentSnapshot;

    // 获取视口顶部对应的文本行及行号
    var topTextViewLine = View.TextViewLines.GetTextViewLineContainingYCoordinate(View.ViewportTop);
    int topLineNumber = topTextViewLine.Start.GetContainingLine().LineNumber;

    // 获取视口底部对应的文本行及行号
    var bottomTextViewLine = View.TextViewLines.GetTextViewLineContainingYCoordinate(View.ViewportBottom);
    int bottomLineNumber = bottomTextViewLine.Start.GetContainingLine().LineNumber;

    // 计算垂直中心行号(整数取整)
    int centerLineNumber = topLineNumber + (bottomLineNumber - topLineNumber) / 2;

    // 定位到中心行并确保居中显示
    var centerLine = snapshot.GetLineFromLineNumber(centerLineNumber);
    View.Caret.MoveTo(centerLine.Start);
    View.ViewScroller.EnsureSpanVisible(centerLine.Extent, EnsureSpanVisibleOptions.AlignCenter);
}

关键代码说明

  • View.TextViewLines.GetTextViewLineContainingYCoordinate():核心方法,将视口Y坐标映射到对应的可见文本行
  • GetContainingLine().LineNumber:将快照位置转换为行号(行号从0开始计数,若需从1起始可自行加1)
  • View.ViewScroller.EnsureSpanVisible():确保跳转后的中心行在视口中居中显示,完成最终的垂直定位

内容的提问来源于stack exchange,提问作者Dess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 21:44:51