views:

227

answers:

1

I tried:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    streamWriter.Write(e.Key.ToString());
}

But I don't know how to convert a Key to string correctly. I also tried:

private void textBox1_TextInput(object sender, TextCompositionEventArgs e)
{
    streamWriter.Write(e.Text);
}

But this event is not called. The farthest I went was:

private string previous = string.Empty;
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    var text = textBox1.Text.Substring(previous.Length);
    streamWriter.Write(text);
    previous = textBox1.Text;
}

But this has problems with character deletion, and many other cases. What should I do?

+2  A: 

The easiest option is to use KeyPress instead of KeyDown.

KeyPressEventArgs.KeyChar provides the actual char, already translated appropriately. Just write this char to your stream directly.


Edit:

After seeing in the comments that this is WPF, not Windows Forms (as tagged), the above will not exist.

That being said, I question your goal here - using a textbox to write to a stream, in a character by character fashion, is always going to be problematic. This is due to what you wrote in your last sentence:

But this has problems with character deletion, and many other cases.

Personally, I would take one of two different approaches:

  1. Use a TextBox as a "buffer", and only send the entire contents to the stream when the focus is lost, etc. This way, the user can delete, etc, as needed, and you always have a complete "string" to work with. This would probably be my first choice, if you want the behavior to be similar to what you're after now.

  2. Don't use a TextBox for this. Use some other control which allows text entry, but not deletion or selection. If you must use a TextBox, and must handle key-by-key streaming, then you should restrict the input (via a behavior or attached property) to only the character you wish, which means disabling deletion.

Reed Copsey
I can't find `KeyPress`. I'm using WPF.
Jader Dias
I found only KeyDown and KeyUp.
Jader Dias
@Jader Dias: Your question is tagged windows-forms, so I was assuming Windows Forms, not WPF...
Reed Copsey
do you know the solution for WPF?
Jader Dias
@Jader Dias: Edited my answer with suggestions.
Reed Copsey
@Reed I created also a Windows Forms project, to test the Keypress
Jader Dias