Underscore acts as a separator C# RTF Box

我是研究僧i 提交于 2019-12-01 12:36:08

问题


I am working on a Winforms application and using Find on the RichTextBox control to find particular keywords to style.

For some reason, despite specifying the WholeWord flag, the Find seems to treat a word with an underscore in it as 2 separate words (and styles the matching half).

The function call is:

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

Why is this happening? Can I override it/fix it somehow?


回答1:


You can, although it's a bit hairy. You need to specify a custom word breaking procedure for your rich text box, and you want to override certain cases and otherwise use the default handler. In C++, it's pretty straightforward; in C#, not so much. This question describes the setup; I've updated it to save the old proc for handling the other cases.

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


来源:https://stackoverflow.com/questions/17871766/underscore-acts-as-a-separator-c-sharp-rtf-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!