■ TextBox 클래스에서 탭 키를 누른 경우 탭 키 대신 공백 문자를 추가하는 방법을 보여준다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
using System.Windows; using System.Windows.Controls; using System.Windows.Input; /// <summary> /// 텍스트 박스 /// </summary> private TextBox textBox; /// <summary> /// 탭 공백 수 /// </summary> private int tabSpaceCount = 4; #region 프리뷰 키 다운시 처리하기 - OnPreviewKeyDown(e) /// <summary> /// 프리뷰 키 다운시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPreviewKeyDown(KeyEventArgs e) { base.OnPreviewKeyDown(e); if(e.Source == this.textBox && e.Key == Key.Tab) { string insert = new string(' ', this.tabSpaceCount); int characterIndex = this.textBox.SelectionStart; int lineIndex = this.textBox.GetLineIndexFromCharacterIndex(characterIndex); if(lineIndex != -1) { int columnIndex = characterIndex - this.textBox.GetCharacterIndexFromLineIndex(lineIndex); insert = new string(' ', this.tabSpaceCount - columnIndex % this.tabSpaceCount); } this.textBox.SelectedText = insert; this.textBox.CaretIndex = this.textBox.SelectionStart + this.textBox.SelectionLength; e.Handled = true; } } #endregion |