开发者

How to redirect a System.Windows.Controls.TextBox input to a stream?

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.Wri开发者_Python百科te(text);
    previous = textBox1.Text;
}

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜