【发布时间】:2016-10-18 20:27:33
【问题描述】:
当我在RichTextBox 中键入内容时,我想在另一个字符串变量中一个接一个地获取每个单词。哪个事件将被触发,我将如何获得它?
【问题讨论】:
标签: c# winforms events richtextbox
当我在RichTextBox 中键入内容时,我想在另一个字符串变量中一个接一个地获取每个单词。哪个事件将被触发,我将如何获得它?
【问题讨论】:
标签: c# winforms events richtextbox
看看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;
}
【讨论】:
只要您在 RichTextBox 中输入内容,就会触发 TextXhanged 事件(惊喜!)
【讨论】:
好的,这就是我在 Richtextbox 的 TextChanged 事件中要做的事情
string[] x = RichTextBox1.Text.Split(new char[]{ ' ' });
遍历变量(字符串数组)x,并将结果放在您需要的地方。 (例如在列表视图、标签等中)
【讨论】:
即使 TextChanged 事件对此可用,我认为如果您有一个已经填充的 TextBox 并只需输入另一个字符,性能也会很糟糕。
因此,要真正让这一切顺利进行,您需要付出一些额外的努力。也许在每个 TextChanged 事件(1000 毫秒)上重新启动一个计时器,这样用户就不会因为快速输入内容而被拦截,并且只有在计时器事件触发时才开始计数。
或者考虑将拆分和计数算法放入后台工作程序中,如果用户要再次向框中输入内容,则可能(或不)取消计数。
好的,这是一个实现示例:
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();
}
}
}
【讨论】: