2013-07-26 29 views
0

我正在使用Winforms應用程序並使用RichTextBox控件上的查找來查找特定關鍵字的樣式。下劃線用作分隔符C#RTF框

由於某些原因,儘管指定了WholeWord標誌,但Find似乎將帶有下劃線的單詞作爲2個單獨的單詞(並對匹配的一半樣式進行樣式化)處理。

函數調用是:

richTextBox1.Find("Keyword", RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord); 

這究竟是爲什麼?我可以重寫它/以某種方式修復它?

回答

1

你可以,雖然它有點毛茸茸的。您需要爲您的富文本框指定custom word breaking procedure,並且您希望重寫某些情況,否則使用默認處理程序。在C++中,它非常簡單;在C#中,不是那麼多。 This question描述了設置;我已經更新它來保存舊的proc來處理其他情況。

namespace q6359774 
{ 
    class MyRichTextBox : RichTextBox 
    { 
     const int EM_SETWORDBREAKPROC = 0x00D0; 
     const int EM_GETWORDBREAKPROC = 0x00D1; 


     delegate int EditWordBreakProc(string lpch, int ichCurrent, int cch, int code); 

    EditWordBreakProc oldEditWordBreakProc; 

     protected override void OnHandleCreated(EventArgs e) 
     { 
      base.OnHandleCreated(e); 
      this.Text = "abcdefghijklmnopqrstuvwxyz-abcdefghijklmnopqrstuvwxyz"; 
      if (!this.DesignMode) 
     { 
       IntPtr oldproc; 
       oldproc = SendMessage(this.Handle, EM_SETWORDBREAKPROC, IntPtr.Zero, Marshal.GetFunctionPointerForDelegate(new EditWordBreakProc(MyEditWordBreakProc))); 
       oldEditWordBreakProc = Marshal.GetDelegateForFunctionPointer(oldproc, typeof(EditWordBreakProc)); 
      } 
     } 

     [DllImport("User32.DLL")] 
     public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); 


     int MyEditWordBreakProc(string lpch, int ichCurrent, int cch, int code) 
     { 
      const int WB_ISDELIMITER = 2; 
      const int WB_CLASSIFY = 3; 
      if (code == WB_ISDELIMITER) 
      { 
       if (lpch.Length == 0 || lpch == null) return 0; 
       char ch = lpch[ichCurrent]; 
       if (ch == '_') 
     { 
        return 0; 
       } 
       else return oldEditWordBreakProc(lpch, ichCurrent, cch, code); 
      } 
      else if (code == WB_CLASSIFY) 
      { 
       if (lpch.Length == 0 || lpch == null) return 0; 
       char ch = lpch[ichCurrent]; 
       var vResult = Char.GetUnicodeCategory(ch); 
       return (int)vResult; 
      } 
      else return oldEditWordBreakProc(lpch, ichCurrent, cch, code); 
     } 
    } 
} 
+0

這還不算太壞!感謝你的回答。 –