跳到主要內容

C# richTextbox hightlight 取得點選單字


一、Hightlight

首先設計disHightlight函數來清除已hightlight單字,再者設計highlight函數來標助搜尋單字,其中利用到indexOf查詢單字位置,查詢到目標後進行單字長度的標註,接著以此向下一目標進行。
1.dishightlight()

 private void dishightlight()
        {
            richTextBox1.Focus();
            richTextBox1.SelectAll();
            richTextBox1.SelectionBackColor = richTextBox1.BackColor;
            richTextBox1.DeselectAll();
            textBox1.Focus();
            textBox1.SelectAll();
        }
2.hightlight
private void highlight(string word)
        {
            dishightlight();
            int tmp = 0;
            while (textBox1.TextLength > 0 && richTextBox1.Text.IndexOf(word, tmp) != -1)
            {
                tmp = richTextBox1.Text.IndexOf(word, tmp);
                richTextBox1.Select(tmp, word.Length);
                richTextBox1.SelectionBackColor = Color.LightGreen;
                tmp += word.Length;
            }
        }

二、取得點選單字

1.首先設計GetTextboxWord來剖析段落中的單字,設計概念主要是當滑鼠移到目標字元後向前向後過濾直到字元非介於a~z或A~Z之間,則順利取出單字。

 public string GetTextboxWord(string input, int position)
        {
            string word = input.ToLower();
            char s = word[position];
            int sp1 = 0, sp2 = word.Length;
            for (int i = position; i > -1; i--)
            {
                char ch = word[i];
                if (ch < 'a' || ch > 'z')
                {
                    sp1 = i+1;
                    break;
                }
            }
            for (int i = position; i < word.Length; i++)
            {
                char ch = word[i];
                if (ch < 'a' || ch > 'z')
                {
                    sp2 = i;
                    break;
                }
            }
            if (sp2 == position) sp1 = sp2;
            return input.Substring(sp1, sp2 - sp1).Replace("\n", "");
        }
2.MouseMove事件

 private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
        {
            RichTextBox rt = (RichTextBox)sender;
            if (rt.Text.Length <= 0) return;
            string word = GetTextboxWord(rt.Text, rt.GetCharIndexFromPosition(e.Location)).Trim();//取得單字
            rt.Cursor = System.Windows.Forms.Cursors.IBeam;//I型游標
            if (!"".Equals(word)) rt.Cursor = System.Windows.Forms.Cursors.Hand;//手狀游標
        }
3.MouseUp事件
private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
        {
            RichTextBox rt = (RichTextBox)sender;
            if (rt.Text.Length <= 0) return;
            string word = GetTextboxWord(rt.Text, rt.GetCharIndexFromPosition(((MouseEventArgs)e).Location)).Trim();
            if (word.Equals("")) return;
            label2.Text = word;//獲取單字
        }

留言

這個網誌中的熱門文章

java西元民國轉換_各種不同格式

C#資料庫操作(新增、修改、刪除、查詢)