English 中文(简体)
c# RTB——无颜无色的惯用文字?
原标题:c# RTB - paste plain text without colours/fonts?

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 there any way how to paste only string and ignore formatting? Thanks!

最佳回答

假设WinForms:尝试:将RichTextBox与一个关键Down活动手,如:

附录:

    private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.V) 
        {
            richTextBox1.Text += (string)Clipboard.GetData("Text"); 
            e.Handled = true; 
        }
    }

[Edit]

在目前的插入点(选举开始)中,向RichTextBox增加Clipster RTF:

private void richTextBox1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.Control && e.KeyCode == Keys.V)  
    { 
            // suspend layout to avoid blinking
            richTextBox2.SuspendLayout();

            // get insertion point
            int insPt = richTextBox2.SelectionStart;

            // preserve text from after insertion pont to end of RTF content
            string postRTFContent = richTextBox2.Text.Substring(insPt);

            // remove the content after the insertion point
            richTextBox2.Text = richTextBox2.Text.Substring(0, insPt);

            // add the clipboard content and then the preserved postRTF content
            richTextBox2.Text += (string)Clipboard.GetData("Text") + postRTFContent;

            // adjust the insertion point to just after the inserted text
            richTextBox2.SelectionStart = richTextBox2.TextLength - postRTFContent.Length;

            // restore layout
            richTextBox2.ResumeLayout();

            // cancel the paste
            e.Handled = true;
    } 
} 

[End Edit]

注0: 案文is中的过去,将假设RichTextBox的现行风格:如果你有“彩色”到“蓝色”:案文中的过去为蓝色。

附注1: 这是我很快聚集在一起的一件事,仅经过几次测试,用WordPad为纸板制造了一些多彩和杂杂交式的RTF:然后在运行时间将它冲入RichTextBox1:它确实使所有的肤色、冷漠等等消失。

由于它没有经过充分测试,使用警告。

附注2: 这显然不会处理通过门图插入或穿梭的情况。

欢迎这一答复的所有论点,如果它不“在......”时,将立即予以放弃。

问题回答

在<代码>KeyDown-event上添加一名手稿,以拦截标准过去和人工插入简单案文:

private void rtb_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.V)
    {
        ((RichTextBox)sender).Paste(DataFormats.GetFormat("Text"));
            e.Handled = true;
    }
}

我正在寻找一个只读写的字典:richtext Box,但在网上找到了解决办法。

How Plaintext- only RichTextBox und a TextBox? 例如,<代码>RichTextBox具有可使用、可使用、可操作、可操作的多功能。

最后,我找到了一种完美的解决办法,将富集层控制权的Cheler文档编为:ARichTextBox。 可转换成浅层模型,然后它不接受格式文本和图像,以及纸板上的类似东西,并像正常的<代码>TextBox格式。 象图像这样的一些老事不能被过去,它通过取消格式而使案文过时。

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

帕斯卡尔皮斯蒂的答复像对我的药店一样。 自2006年以来 Im 采用vb.net I, 认为我把我的翻译代码张贴给他人:

Imports System.Runtime.InteropServices
Imports System.ComponentModel

Public Class MyRichTextBox
    Inherits Windows.Forms.RichTextBox

    Public Const WM_USER As Integer = &H400
    Public Const EM_SETTEXTMODE As Integer = WM_USER + 89
    Public Const EM_GETTEXTMODE As Integer = WM_USER + 90

     EM_SETTEXTMODE/EM_GETTEXTMODE flags
    Public Const TM_PLAINTEXT As Integer = 1
    Public Const TM_RICHTEXT As Integer = 2            Default behavior 
    Public Const TM_SINGLELEVELUNDO As Integer = 4
    Public Const TM_MULTILEVELUNDO As Integer = 8      Default behavior 
    Public Const TM_SINGLECODEPAGE As Integer = 16
    Public Const TM_MULTICODEPAGE As Integer = 32      Default behavior

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
    End Function

    Private _plainTextMode As Boolean = False
    <DefaultValue(False),
      Browsable(True)>
    Public Property PlainTextMode As Boolean
        Get
            Return _plainTextMode
        End Get
        Set(value As Boolean)
            _plainTextMode = value

            If (Me.IsHandleCreated) Then
                Dim mode As IntPtr = If(value, TM_PLAINTEXT, TM_RICHTEXT)
                SendMessage(Handle, EM_SETTEXTMODE, mode, IntPtr.Zero)
            End If
        End Set
    End Property

    Protected Overrides Sub OnHandleCreated(e As EventArgs)
         For some reason it worked for me only if I manipulated the created
         handle before calling the base method.
        Me.PlainTextMode = _plainTextMode

        MyBase.OnHandleCreated(e)
    End Sub
End Class

而RichTextBox拥有SelectionFont 财产,因此,例如,你可以:

Font courier;
courier = new Font("Courier new", 10f, FontStyle.Regular);
myRtb.SelectionFont = courier;
myRtb.Font = courier; //So the typed text is also the same font

如果案文过去,将自动格式。

你们也可以使用

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.V)
    {
        richTextBox1.SelectedText = (string)Clipboard.GetData("Text");
        e.Handled = true;
    }
}

我之所以取得这一成就,是因为在广播电视局内容发生变化时,要为整个广播电视局提供名声和颜色。 由于进入箱不需要处理大量的文本,这对我来说是很有价值的。

public FormMain()
{
    InitializeComponent();
    txtRtb.TextChanged += txtRtb_TextChanged;
}

void txtRtb_TextChanged(object sender, EventArgs e)
{
    RichTextBox rtb = (RichTextBox)sender;
    rtb.SelectAll();
    rtb.SelectionFont = rtb.Font;
    rtb.SelectionColor = System.Drawing.SystemColors.WindowText;
    rtb.Select(rtb.TextLength,0);
}

我的解决办法

private void OnCommandExecuting(object sender, Telerik.Windows.Documents.RichTextBoxCommands.CommandExecutingEventArgs e)
{
    if (e.Command is PasteCommand)
    {
        //override paste when clipboard comes from out of RichTextBox (plain text)
        var documentFromClipboard = ClipboardEx.GetDocumentFromClipboard("RadDocumentGUID");
        if (documentFromClipboard == null)
        {
            (sender as RichTextBox).Insert(Clipboard.GetText());
            e.Cancel = true;
        }
    }
}

对我来说,这样做非常简单:

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

由于Text 财产本质上没有格式重新制定RTF案文,然后将案文财产放在原始投入中去除可能已经过去的任何特殊物品。

简单,但当申请开放时,纸板上的所有内容都处于便衣。

private void timer2_Tick(object sender, EventArgs e)
        {
            string paste = Clipboard.GetText();
            Clipboard.SetText(paste);
        }




相关问题
Bring window to foreground after Mutex fails

I was wondering if someone can tell me what would be the best way to bring my application to the foreground if a mutex was not able to be created for a new instance. E.g.: Application X is running ...

How to start WinForm app minimized to tray?

I ve successfully created an app that minimizes to the tray using a NotifyIcon. When the form is manually closed it is successfully hidden from the desktop, taskbar, and alt-tab. The problem occurs ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

Handle DataTable.DataRow cell change event

I have a DataTable that has several DataColumns and DataRow. Now i would like to handle an event when cell of this DataRow is changed. How to do this in c#?

Apparent Memory Leak in DataGridView

How do you force a DataGridView to release its reference to a bound DataSet? We have a rather large dataset being displayed in a DataGridView and noticed that resources were not being freed after the ...

ALT Key Shortcuts Hidden

I am using VS2008 and creating forms. By default, the underscore of the character in a textbox when using an ampersand is not shown when I run the application. ex. "&Goto Here" is not ...

WPF-XAML window in Winforms Application

I have a Winforms application coded in VS C# 2008 and want to insert a WPF window into the window pane of Winforms application. Could you explain me how this is done.