非IT企業に勤める中年サラリーマンのIT日記

非IT企業でしかもITとは全く関係ない部署にいる中年エンジニア。唯一の趣味がプログラミングという”自称”プログラマー。

C#のテキストボックスで行番号を取得する方法

   

テキストエディターなんかで、カーソル移動するとそれに伴って行番号が表示されています。これを作る方法を紹介します。

VS Codeだと以下の赤矢印のような表示です。

[ad#top-1]

やり方はいろいろありますが、今回の例では、カーソル位置以前のテキストを改行文字「\n」で配列化して、その要素数から現在位置(行)を特定する方法です。

private int getLine(){
  if(textBox.ImeMode==ImeMode.Hiragana) return -1;</pre>

  int pos = textBox.Text.Substring(0, textBox.SelectionStart).Split('\n').Length;
  return pos;
}

 

このメソッドをKeyUpイベントやMouseUpイベントで動かして返値を表示させると行数が取得できます。注意すべきはKeyDown, MouseDownイベントではダメだということです。Downイベント時にはまだカーソルが移動していないので前の1つ前のカーソル位置を読み取ってしまうので。

下図がその例。

 

上図のソースコードは下記の通りです。これをコピペして実行してください。

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

class GetLine{
  static void Main(string[] args){
    Application.Run(new MainWindow(args));
  }
}

class MainWindow : Form{
  private RichTextBox textBox;
  private Label label;

  public MainWindow(string[] args){
    this.StartPosition = FormStartPosition.CenterScreen;
    this.Width = 800;
    this.Height =600;
    this.Text = "テキストボックステスト";

    textBox = new RichTextBox(){
      Dock = DockStyle.Fill,
      Font = new Font("MS ゴシック", 18),
      AcceptsTab = true,
      WordWrap = false,
      Parent=this,
    };
    textBox.KeyUp += new KeyEventHandler(keyUpped);
    textBox.MouseUp += new MouseEventHandler(MouseUpped);

    label = new Label(){
      Size = new Size(40, 40),
      Font = new Font("MS ゴシック", 18),
      Dock = DockStyle.Top,
      Parent=this,
    };
  }

  //keyUpイベントハンドラ
  private void keyUpped(object sender, KeyEventArgs e){
    label.Text = this.getLine() + "行目";
  }

  private void MouseUpped(object sender, MouseEventArgs e){
    label.Text = this.getLine() + "行目";
  }

  //行Noを取得
  private int getLine(){
    if(textBox.ImeMode==ImeMode.Hiragana) return -1;
    int pos = textBox.Text.Substring(0, textBox.SelectionStart).Split('\n').Length;
    return pos;
  }
}
 

 

[ad#ad-1]

スポンサーリンク

 - C#応用編