기계는 거짓말하지 않는다

C# Windows Forms 키 입력 필터 본문

C#

C# Windows Forms 키 입력 필터

KillinTime 2021. 7. 10. 19:12

숫자만 입력 또는 숫자와 소수점만 입력 (지우기는 가능함)

private void OnlyDigit_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar)) // 숫자만 입력
    {
        e.Handled = true;
    }
}

private void OnlyDigitAndDecimalPoint_KeyPress(object sender, KeyPressEventArgs e) // 숫자, 소수점만 입력
{
    if (!(char.IsDigit(e.KeyChar) || e.KeyChar == '.'))
    {
        e.Handled = true;
    }
}

private void OnlyChar_KeyPress(object sender, KeyPressEventArgs e) // 문자만 입력
{
    if (char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

Ctrl + V 를 이용하면 이벤트 적용이 되어 있더라도 복사가 되기 때문에 따로 처리를 하거나 예외 처리를 해주어야 한다.

Comments