Share via


Cómo: Habilitar operaciones de arrastrar y colocar con el control RichTextBox de formularios Windows Forms

Actualización: noviembre 2007

Las operaciones de arrastrar y colocar con el control RichTextBox de formularios Windows Forms se realizan mediante el control de los eventos DragEnter y DragDrop. Por tanto, estas operaciones son extremadamente sencillas con el control RichTextBox.

Para habilitar las operaciones de arrastrar en un control RichTextBox

  1. Establezca la propiedad AllowDrop del control RichTextBox en true.

  2. Escriba código en el controlador del evento DragEnter. Utilice una instrucción if para asegurarse de que los datos que se está arrastrando son de un tipo aceptable (en este caso, text). La propiedad DragEventArgs.Effect puede estar establecida en cualquier valor de la enumeración DragDropEffects.

    Private Sub RichTextBox1_DragEnter(ByVal sender As Object, _ 
       ByVal e As System.Windows.Forms.DragEventArgs) _ 
       Handles RichTextBox1.DragEnter
       If (e.Data.GetDataPresent(DataFormats.Text)) Then
          e.Effect = DragDropEffects.Copy
       Else
          e.Effect = DragDropEffects.None
       End If
    End Sub
    
    private void richTextBox1_DragEnter(object sender, 
    System.Windows.Forms.DragEventArgs e)
    {
       if (e.Data.GetDataPresent(DataFormats.Text)) 
          e.Effect = DragDropEffects.Copy;
       else
          e.Effect = DragDropEffects.None;
    }
    
    private void richTextBox1_DragEnter(Object sender,
    System.Windows.Forms.DragEventArgs e)
    {
       if (e.get_Data().GetDataPresent(DataFormats.Text))
          e.set_Effect(DragDropEffects.Copy);
       else
          e.set_Effect(DragDropEffects.None);
    }
    
    private:
       void richTextBox1_DragEnter(System::Object ^  sender,
          System::Windows::Forms::DragEventArgs ^  e)
       {
          if (e->Data->GetDataPresent(DataFormats::Text))
             e->Effect = DragDropEffects::Copy;
          else
             e->Effect = DragDropEffects::None;
       }
    

    (Visual C#, Visual J# y Visual C++) Coloque el código siguiente en el constructor del formulario para registrar el controlador de eventos.

    this.richTextBox1.DragEnter += new
        System.Windows.Forms.DragEventHandler
        (this.richTextBox1_DragEnter);
    
    this.richTextBox1.add_DragEnter(new
       System.Windows.Forms.DragEventHandler(
          this.richTextBox1_DragEnter));
    
    this->richTextBox1->DragEnter += gcnew
       System::Windows::Forms::DragEventHandler
       (this, &Form1::richTextBox1_DragEnter);
    
  3. Escriba código para controlar el evento DragDrop. Utilice el método DataObject.GetData para recuperar los datos que se van a arrastrar.

    En el ejemplo siguiente, el código establece la propiedad Text del control RichTextBox igual a los datos que se van a arrastrar. Si ya hay texto en el control RichTextBox, el texto arrastrado se insertará en el punto de inserción.

    Private Sub RichTextBox1_DragDrop(ByVal sender As Object, _ 
       ByVal e As System.Windows.Forms.DragEventArgs) _ 
       Handles RichTextBox1.DragDrop
       Dim i As Int16 
       Dim s As String
    
       ' Get start position to drop the text.
       i = RichTextBox1.SelectionStart
       s = RichTextBox1.Text.Substring(i)
       RichTextBox1.Text = RichTextBox1.Text.Substring(0, i)
    
       ' Drop the text on to the RichTextBox.
       RichTextBox1.Text = RichTextBox1.Text + _
          e.Data.GetData(DataFormats.Text).ToString()
       RichTextBox1.Text = RichTextBox1.Text + s
    End Sub
    
    private void richTextBox1_DragDrop(object sender, 
    System.Windows.Forms.DragEventArgs e)
    {
       int i;
       String s;
    
       // Get start position to drop the text.
       i = richTextBox1.SelectionStart;
       s = richTextBox1.Text.Substring(i);
       richTextBox1.Text = richTextBox1.Text.Substring(0,i);
    
       // Drop the text on to the RichTextBox.
       richTextBox1.Text = richTextBox1.Text + 
          e.Data.GetData(DataFormats.Text).ToString();
       richTextBox1.Text = richTextBox1.Text + s;
    }
    
    private void richTextBox1_DragDrop(Object sender,
    System.Windows.Forms.DragEventArgs e)
    {
       int i;
       String s;
    
       // Get start position to drop the text.
       i = richTextBox1.get_SelectionStart();
       s = richTextBox1.get_Text().Substring(i);
       richTextBox1.set_Text(richTextBox1.get_Text().Substring(0, i));
    
       // Drop the text on to the RichTextBox.
       richTextBox1.set_Text(richTextBox1.get_Text() +
          e.get_Data().GetData(DataFormats.Text).ToString());
       richTextBox1.set_Text(richTextBox1.get_Text() + s);
    }
    
    private:
       System::Void richTextBox1_DragDrop(System::Object ^  sender,
          System::Windows::Forms::DragEventArgs ^  e)
       {
          int i;
          String ^s;
    
       // Get start position to drop the text.
       i = richTextBox1->SelectionStart;
       s = richTextBox1->Text->Substring(i);
       richTextBox1->Text = richTextBox1->Text->Substring(0,i);
    
       // Drop the text on to the RichTextBox.
       String ^str = String::Concat(richTextBox1->Text, e->Data
       ->GetData(DataFormats->Text)->ToString()); 
       richTextBox1->Text = String::Concat(str, s);
       }
    

    (Visual C#, Visual J# y Visual C++) Coloque el código siguiente en el constructor del formulario para registrar el controlador de eventos.

    this.richTextBox1.DragDrop += new
        System.Windows.Forms.DragEventHandler
        (this.richTextBox1_DragDrop);
    
    this.richTextBox1.add_DragDrop(new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragDrop));
    
    this->richTextBox1->DragDrop += gcnew 
       System::Windows::Forms::DragEventHandler
       (this, &Form1::richTextBox1_DragDrop);
    

Para probar la funcionalidad de arrastrar y colocar en la aplicación

  1. Guarde y genere la aplicación. Mientras se está ejecutando, ejecute WordPad.

    WordPad es un editor de texto instalado por Windows que permite ejecutar operaciones de arrastrar y colocar. Para obtener acceso a esta aplicación, haga clic en el botón Inicio, seleccione Ejecutar, escriba WordPad en el cuadro de texto del cuadro de diálogo Ejecutar y, a continuación, haga clic en Aceptar.

  2. Una vez abierto WordPad, escriba una cadena de texto en él. Por medio del mouse (ratón), seleccione el texto y arrástrelo al control RichTextBox de la aplicación para Windows.

    Observe que, cuando se mueve el mouse sobre el control RichTextBox (y, por tanto, se produce el evento DragEnter), el cursor cambia y es posible colocar el texto seleccionado en el control RichTextBox.

    Cuando suelte el botón del mouse, se colocará el texto seleccionado (es decir, se producirá el evento DragDrop) y se insertará dentro del control RichTextBox.

Vea también

Tareas

Cómo: Llevar a cabo operaciones de arrastrar y colocar entre aplicaciones

Referencia

RichTextBox

Otros recursos

RichTextBox (Control, formularios Windows Forms)

Controles que se utilizan en formularios Windows Forms