C#: TextBoxやRichTextBox: 複数行選択+「Tab」キーで一括でTabを入れる方法
テキストエディターの標準的な機能でもあるのですが、テキストを複数行選択して「Tab」キーを押すと、その行すべてにTabが入ります。また、「Shift」+「Tab」キーでTabが消えていくという機能があります。その作り方の紹介です。
こんなやつです。↓
※GIFアニメはこちらで作成しました。
[ad#top-1]
目次
まず複数選択時にTab機能を受け付けないようにする
複数選択してTabキーを押すと、そのテキストは消えてTabが入ってしまいます。
まずは、複数選択時にTab機能を受け付けないようにする必要があります。
private void keyPressed(object sender, KeyPressEventArgs e){ if(e.KeyChar == "\t"[0] && textBox.SelectionLength>0) e.Handled=true; } /* textBoxにKeyPressEventHandlerをあてています。 textBox.KeyPress += new KeyPressEventHandler(keyPressed); */
複数行選択の状態で「Tab」キー押すと一括Tab挿入
こちらが「Tab」キー押して一括Tab挿入するソースコードです。
private void keyDowned(object sender, KeyEventArgs e){ //[Tab]キー if(e.KeyCode == Keys.Tab && textBox.SelectionLength>0 && !e.Shift){ // 選択した行をすべて包む string text = textBox.Text + "\n"; int selectstart = textBox.SelectionStart-1; if(selectstart<0) selectstart=0; int st = text.LastIndexOf("\n", selectstart) + 1; int en = text.IndexOf("\n", textBox.SelectionStart+textBox.SelectionLength-1); textBox.Select(st, en-st); text = textBox.SelectedText; //先頭にTab挿入 text = "\t" + text; int pos=0; for(;;){ pos = text.IndexOf("\n", pos); if(pos<0) break; text = text.Insert(pos+1, "\t"); pos+=2; } //TextBoxに修正済みテキスト挿入 textBox.SelectedText = text; textBox.Select(st, text.Length); } } /* textBoxにKeyEventHandlerをあてています。 textBox.KeyPress += new KeyPressEventHandler(keyPressed); */
複数行選択の状態で「Shift」+「Tab」キー押すとTab削除
こちらが「Shift」+「Tab」キー押してTab削除するソースコードです。上のkeyDownedメソッド内に挿入してください。
//[Shift]+[Tab]キー if(e.KeyCode == Keys.Tab && textBox.SelectionLength>0 && e.Shift){ // 選択した行をすべて包む string text = textBox.Text + "\n"; int selectstart = textBox.SelectionStart-1; if(selectstart<0) selectstart=0; int st = text.LastIndexOf("\n", selectstart) + 1; int en = text.IndexOf("\n", textBox.SelectionStart+textBox.SelectionLength-1); textBox.Select(st, en-st); text = textBox.SelectedText; //Shift+Tabキーなら先頭のTab削除 if(text.Substring(0, 1)=="\t") text = text.Remove(0, 1); text = text.Replace("\n\t", "\n"); //TextBoxに修正済みテキスト挿入 textBox.SelectedText = text; textBox.Select(st, text.Length); }
ソースコード全文
ソースコード全文はこちらです。
Windows APIでフォントが勝手に変わらない処置と、タブサイズを3に設定しています。
[ad#ad-1]
スポンサーリンク