J'ai une question. Des exemples que je trouve sont sur une "KeyPress" et ils ne fonctionnent plus sur WPF
Pouvez-vous me dire comment autoriser uniquement l'écriture de clés spécifiées à partir du clavier sur la zone de texte WPF? Je connais les fonctions keyUp et Down, mais comment définir les lettres que je veux y taper?
Je pense que ce sera plus facile, si je poste mon code et que je vous dis ce que je veux faire. Que changer ici?
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
//something here to only allow "A" key to be pressed and displeyed into textbox
if (e.Key == Key.A)
{
stoper.Start();
}
}
private void textBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.A)
{
//here i stop the stopwatch to count time of pressing the key
stoper.Stop();
string aS = stoper.ElapsedMilliseconds.ToString();
int aI = Convert.ToInt32(aS);
stoper.Reset();
}
}
Réponses:
1 pour la réponse № 1Vous pouvez utiliser PreviewKeyDown et utilise e.Key
pour filtrer ce dont vous avez besoin.
Ou, dans tout lieu de votre code que vous pouvez utiliser Clavier classe:
if (Keyboard.IsKeyDown(Key.E)) { /* your code */ }
METTRE À JOUR:
Pour interdire une clé, vous devez définir l'événement comme géré:
if (e.Key == Key.E)
{
e.Handled = true;
MessageBox.Show($"{e.Key.ToString()} is forbidden");
}
0 pour la réponse № 2
Cette chose fonctionne très bien pour moi (merci pour @JohnyL):
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
//something here to only allow "A" key to be pressed and displeyed into textbox
if (e.Key == Key.A)
{
stoper.Start();
}
else
e.Handled = true;
}
private void textBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.A)
{
//here i stop the stopwatch to count time of pressing the key
stoper.Stop();
string aS = stoper.ElapsedMilliseconds.ToString();
int aI = Convert.ToInt32(aS);
stoper.Reset();
}
}