Domanda

Qual è il modo migliore per impedire che determinate chiavi di input vengano utilizzate in una TextBox senza bloccare tasti speciali come Ctrl-V / Ctrl-C?

Ad esempio, consentendo all'utente di inserire solo un sottoinsieme di caratteri o numeri come A o B o C e nient'altro.

È stato utile?

Soluzione

Vorrei usare l'evento keydown e usare l'e.cancel per fermare la chiave se la chiave non è consentita. Se volessi farlo in più punti, farei un controllo utente che eredita una casella di testo e quindi aggiungere una proprietà AllowChars o DisallowedChars che la gestisca per me. Ho in giro un paio di varianti che utilizzo di volta in volta, alcune per consentire formattazione e input di denaro, altre per la modifica del tempo e così via.

La cosa buona da fare come controllo utente è che puoi aggiungerlo e farlo nella tua casella di testo killer. ;)

Altri suggerimenti

Ho usato il controllo Masked Textbox per i winform. C'è una spiegazione più lunga al riguardo qui . In sostanza, non consente input che non corrispondono ai criteri per il campo. Se non vuoi che le persone digitino altro che numeri, semplicemente non permetterebbe loro di digitare altro che numeri.

Questo è il modo in cui lo gestisco di solito.

Regex regex = new Regex("[0-9]|\b");            
e.Handled = !(regex.IsMatch(e.KeyChar.ToString()));

Ciò consentirà solo caratteri numerici e backspace. Il problema è che in questo caso non ti sarà permesso usare i tasti di controllo. Vorrei creare la mia classe di casella di testo se si desidera mantenere quella funzionalità.

Ho scoperto che l'unica soluzione funzionante si è conclusa facendo un controllo preliminare della pressione dei tasti in ProcessCmdKey per Ctrl-V, Ctrl-C, Elimina o Backspace e facendo un'ulteriore convalida se non fosse una di queste chiavi in l'evento KeyPress usando un'espressione regolare.

Questo probabilmente non è il modo migliore ma ha funzionato nelle mie circostanze.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // check the key to see if it should be handled in the OnKeyPress method
    // the reasons for doing this check here is:
    // 1. The KeyDown event sees certain keypresses differently, e.g NumKeypad 1 is seen as a lowercase A
    // 2. The KeyPress event cannot see Modifer keys so cannot see Ctrl-C,Ctrl-V etc.
    // The functionality of the ProcessCmdKey has not changed, it is simply doing a precheck before the 
    // KeyPress event runs
    switch (keyData)
    {
        case Keys.V | Keys.Control :
        case Keys.C | Keys.Control :
        case Keys.X | Keys.Control :
        case Keys.Back :
        case Keys.Delete :
            this._handleKey = true;
            break;
        default:
            this._handleKey = false;
            break;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}


protected override void OnKeyPress(KeyPressEventArgs e)
{
    if (String.IsNullOrEmpty(this._ValidCharExpression))
    {
        this._handleKey = true;
    }
    else if (!this._handleKey)
    {
        // this is the final check to see if the key should be handled
        // checks the key code against a validation expression and handles the key if it matches
        // the expression should be in the form of a Regular Expression character class
        // e.g. [0-9\.\-] would allow decimal numbers and negative, this does not enforce order, just a set of valid characters
        // [A-Za-z0-9\-_\@\.] would be all the valid characters for an email
        this._handleKey = Regex.Match(e.KeyChar.ToString(), this._ValidCharExpression).Success;
    }
    if (this._handleKey)
    {
        base.OnKeyPress(e);
        this._handleKey = false;
    }
    else
    {
        e.Handled = true;
    }

}

È possibile utilizzare l'evento TextChanged per la casella di testo.

    private void txtInput_TextChanged(object sender, EventArgs e)
    {
        if (txtInput.Text.ToUpper() == "A" || txtInput.Text.ToUpper() == "B")
        {
            //invalid entry logic here
        }
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top