当我在RichTextBox
中输入内容时,我想逐个在另一个字符串变量中逐个获取每个单词。将会触发哪个事件,我将如何获得它?
答案 0 :(得分:3)
看看TextChanged event。每当控件中的文本发生更改时,此事件都会触发。您可以订阅它,并在事件处理程序中拆分文本以单独获取每个单词,如下所示:
// subscribe to event elsewhere in your class
this.myRichTextBox.TextChanged += this.TextChangedHandler;
// ...
private void TextChangedHandler(object sender, EventArgs e)
{
string currentText = this.myRichTextBox.Text;
var words = currentText.Split(new [] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
// whatever else you want to do with words here
}
修改强>
如果您想获取当前输入的字词,只需使用IEnumerable.LastOrDefault:
即可var words = currentText.Split(new [] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
string currentlyTyped = words.LastOrDefault();
如果您担心每次键入时分割单词的性能/用户体验问题,您只需分析最后一个字符并将其附加到某些currentWord
:
// in your event handler
char newestChar = this.myRichTextBox.Text.LastOrDefault();
if (char.IsWhiteSpace(newestChar) || char.IsControl(newestChar))
{
this.currentWord = ""; // entered whitespace, reset current
}
else
{
this.currentWord = currentWord + newestChar;
}
答案 1 :(得分:0)
只要您在RichTextBox中键入内容,就会引发TextXhanged事件(惊喜!)
答案 2 :(得分:0)
好的,这就是我在Richtextbox的TextChanged事件中要做的事情
string[] x = RichTextBox1.Text.Split(new char[]{ ' ' });
遍历变量(sting array)x,并将结果放在需要的位置。 (如列表视图,标签等)。
答案 3 :(得分:0)
即使TextChanged事件可以使用,我认为如果你已经填充了TextBox并且只是输入另一个字符,性能将会很糟糕。
因此,为了让这项工作顺利进行,您需要额外的努力。也许在每个TextChanged事件(1000ms)上重新启动一个计时器,因此用户不会通过快速输入内容而被截获,只有在计时器事件被触发时才启动单词计数。
或者考虑将分割和计数算法放入后台工作程序中,如果用户要再次在框中输入内容,可以(或不)取消计数。
好的,这是一个实现示例:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApplication
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
RestartTimer();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var textToAnalyze = textBox1.Text;
if (e.Cancel)
{
// ToDo: if we have a more complex algorithm check this
// variable regulary to abort your count algorithm.
}
var words = textToAnalyze.Split();
e.Result = words.Length;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled
|| e.Error != null)
{
// ToDo: Something bad happened and no results are available.
}
var count = e.Result as int?;
if (count != null)
{
var message = String.Format("We found {0} words in the text.", count.Value);
MessageBox.Show(message);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
// ToDo: If we already run, should we let it run or restart it?
return;
}
timer1.Stop();
backgroundWorker1.RunWorkerAsync();
}
private void RestartTimer()
{
if (backgroundWorker1.IsBusy)
{
// If BackgroundWorker should stop it's counting
backgroundWorker1.CancelAsync();
}
timer1.Stop();
timer1.Start();
}
}
}