첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

■ TextBox 클래스에서 탭 키를 누른 경우 탭 키 대신 공백 문자를 추가하는 방법을 보여준다.

 

▶ 예제 코드 (C#)

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
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요