键入时的 RichTextBox 事件

发布于 2024-11-02 09:40:38 字数 81 浏览 1 评论 0原文

当我在 RichTextBox 中输入内容时,我想在另一个字符串变量中逐个获取每个单词。哪个事件将被触发?我将如何获得它?

I want to fetch each word individually one by one in another string variable when I type something in a RichTextBox. Which event will be fired on it and how will I get it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我很OK 2024-11-09 09:40:38

看一下 TextChanged 事件。每当控件中的文本发生更改时,就会触发此事件。您可以订阅它,并在事件处理程序中拆分文本以单独获取每个单词,如下所示:

// 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;
}

Take a look at TextChanged event. Whenever text in control changes, this event fires. You can subscribe to it, and in event handler split your text to get each word individually, like this:

// 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
}

Edit:

If you want to get currently typed word, you could simply use IEnumerable.LastOrDefault:

var words = currentText.Split(new [] { ' ' }, 
                              StringSplitOptions.RemoveEmptyEntries);
string currentlyTyped = words.LastOrDefault();

If you are worried about performance/user experience problems with splitting words everytime you type, you can just analyse last character and append it to some 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;
}
挖个坑埋了你 2024-11-09 09:40:38

只需 TextXhanged 每当您在 RichTextBox 中输入一些内容(惊讶!)

Simply TextXhanged Event will be raised whenever you type somthing in the RichTextBox (surprise!)

最初的梦 2024-11-09 09:40:38

好的,这就是我在 Richtextbox 的 TextChanged 事件中要做的

string[] x = RichTextBox1.Text.Split(new char[]{ ' ' });

迭代变量(字符串数组) x,并将结果放在您需要的地方。 (如列表视图、标签等)

ok this is what I would do in the TextChanged Event of the Richtextbox

string[] x = RichTextBox1.Text.Split(new char[]{ ' ' });

Iterate through the variable (sting array) x, and place the results where you need it. (like in a listview, a label etc.)

百变从容 2024-11-09 09:40:38

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

Even if the TextChanged event is usable for that i think the performance will be horrible if you have an already filled TextBox and simply enter another character.

So to get this really to work smooth you need some additional efforts. Maybe restart a timer on every TextChanged event (1000ms), so the user won't be intercepted by entering something fast and start the word counting only when the timer event is fired up.

Or think about putting the split and count algorithm into a background worker and maybe (or not) cancel the count if the user is going to enter something again into the box.

Update

Ok, here is an implementation example:

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();
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文