c# RTB - paste plain text without colours/fonts?

前端 未结 10 1209
感动是毒
感动是毒 2021-02-06 07:42

I am using Rich Text object in my C# application. The only issue I am having is that when user pastes formated text from another app, it remains formated which I cannot have. Is

10条回答
  •  醉话见心
    2021-02-06 08:12

    I was searching for a plaintext-only richtextbox but haven't found the solution online.

    Why Plaintext-only RichTextBox instead of a TextBox? For example because RichTextBox has usable undo/redo functionality and much more.

    Finally I found a perfect solution by digging into the C header files of the richedit control: A RichTextBox can be switched into plaintext mode, after that it doesn't accept formatted text and images and similar things from the clipboard and behaves like a normal TextBox formattingwise. Fancy things like images can not be pasted and it pastes formatted text by removing the formatting.

    class PlainRichTextBox : RichTextBox
    {
        const int WM_USER = 0x400;
        const int EM_SETTEXTMODE = WM_USER + 89;
        const int EM_GETTEXTMODE = WM_USER + 90;
    
        // EM_SETTEXTMODE/EM_GETTEXTMODE flags
        const int TM_PLAINTEXT = 1;
        const int TM_RICHTEXT = 2;          // Default behavior 
        const int TM_SINGLELEVELUNDO = 4;
        const int TM_MULTILEVELUNDO = 8;    // Default behavior 
        const int TM_SINGLECODEPAGE = 16;
        const int TM_MULTICODEPAGE = 32;    // Default behavior 
    
        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
    
        bool m_PlainTextMode;
    
        // If this property doesn't work for you from the designer for some reason
        // (for example framework version...) then set this property from outside
        // the designer then uncomment the Browsable and DesignerSerializationVisibility
        // attributes and set the Property from your component initializer code
        // that runs after the designer's code.
        [DefaultValue(false)]
        //[Browsable(false)]
        //[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool PlainTextMode
        {
            get
            {
                return m_PlainTextMode;
            }
            set
            {
                m_PlainTextMode = value;
                if (IsHandleCreated)
                {
                    IntPtr mode = value ? (IntPtr)TM_PLAINTEXT : (IntPtr)TM_RICHTEXT;
                    SendMessage(Handle, EM_SETTEXTMODE, mode, IntPtr.Zero);
                }
            }
        }
    
        protected override void OnHandleCreated(EventArgs e)
        {
            // For some reason it worked for me only if I manipulated the created
            // handle before calling the base method.
            PlainTextMode = m_PlainTextMode;
            base.OnHandleCreated(e);
        }
    }
    

提交回复
热议问题