在按下键之后,将此代码向下append text
发送到textBox
。它为每个按键写入一行。请问是否有任何好的解决方案可以收集例如5键按下并将它们写在一行中?
private void User_KeyPress(object sender, KeyPressEventArgs e)
{
textBox.AppendText(string.Format("You Wrote: - {0}\n", e.KeyChar));
textBox.ScrollToCaret();
}
例如,MOUSE不会被写成:
You Wrote: M;
You Wrote: O;
You Wrote: U;
You Wrote: S;
You Wrote: E
但输出将是:
You wrote: MOUSE
答案 0 :(得分:1)
请勿致电textBox.AppendText
。追加添加到现有字符串并组合它们。
你想写一些像textBox.Text = String.Format(...)
您应该在对象中创建一个私有变量,以跟踪所有字符并附加到该字符。拥有User_KeyPress
方法的类应该具有如下变量:
private string _keysPressed = String.Empty;
现在在你的方法中你可以像这样追加和输出:
private void User_KeyPress(object sender, KeyPressEventArgs e)
{
_keysPressed += e.KeyChar;
textBox.Text = String.Format("You Wrote: - {0}\n", _keysPressed);
textBox.ScrollToCaret();
}
答案 1 :(得分:1)
可能是这样的:
string testCaptured = string.Empty;
int keyPressed = 0;
private void User_KeyPress(object sender, KeyPressEventArgs e)
{
if (keyPressed < 5)
{
testCaptured += e.keyChar;
keyPressed++;
}
else
{
textBox.Text = string.Format("You Wrote: - {0}\n", testCaptured);
textBox.ScrollToCaret();
}
}
答案 2 :(得分:1)
您可以缓冲按键直到达到阈值,然后输出整个缓冲区的内容。
e.g。
Queue<char> _buffer = new Queue<char>();
private void User_KeyPress(object sender, KeyPressEventArgs e)
{
_buffer.Enqueue(e.KeyChar);
if(_buffer.Count > 5)
{
StringBuilder sb = new StringBuilder("You Wrote: ");
while(_buffer.Count > 0)
sb.AppendFormat(" {0}", _buffer.Dequeue());
Console.WriteLine(sb.ToString());
}
}