2013-10-08 33 views
0

你好这个代码按下后按下append texttextBox。它为每个按键写一行。请问是否有任何好的解决方案来收集例如5个按键并将它们写入一行?收集多个按键事件

  private void User_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     textBox.AppendText(string.Format("You Wrote: - {0}\n", e.KeyChar)); 
     textBox.ScrollToCaret(); 
    } 

例如鼠标不会这样写:

You Wrote: M; You Wrote: O; You Wrote: U; You Wrote: S; You Wrote: E

但输出将是:

You wrote: MOUSE

回答

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(); 
    } 
} 
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(); 
} 
+0

感谢您的回答,但不会使用'.AppendText',这意味着之前编写的内容将被新的'keypress'事件重写? – Marek

+0

更新了我的答案。 –

1

您可以缓存按键直到达到阈值,然后输出整个缓冲区的内容。

例如

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()); 
    } 
}