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

前端 未结 10 1196
感动是毒
感动是毒 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

    There is a very simple way to do this that is working well for me:

    private bool updatingText;
    
    public MyForm() {
        InitializeComponent();
        inputTextBox.TextChanged += inputTextBox_TextChanged;
    }
    private void inputTextBox_TextChanged(object sender, EventArgs e)
    {
        if (updatingText)
        {
            return;
        }
        updatingText = true;
        try
        {
            var i = inputTextBox.SelectionStart;
            var text = inputTextBox.Text;
            inputTextBox.Rtf = "";
            inputTextBox.Text = text;
            inputTextBox.SelectionStart = i;
        }
        catch (Exception){}
        updatingText = false;
    }
    

    Since the Text property is inherently without formatting resetting the RTF text then setting the text property to the raw input removes any of the special items that may have been pasted in.

提交回复
热议问题