Pregunta

¿Hay alguna forma de hacer que un control, como un cuadro de texto, se pueda arrastrar y soltar en C #?

Quiero que el usuario tenga la capacidad de hacer clic y mantener presionado el control con el mouse, arrastrarlo por su superficie y soltarlo en cualquier lugar dentro de esa superficie.

¿Alguien tiene alguna idea de cómo implementar esto?

¿Fue útil?

Solución

Esta respuesta me ayudó a mucho. Funciona muy bien en cualquier tipo de Control y Contenedor.

Otros consejos

Si su control se mueve dentro de un contenedor (por ejemplo, panel), puede anular los eventos OnMouseDown / OnMouseMove y ajustar la propiedad Location del control.

Según su pregunta, no parece que necesite arrastrar y soltar completamente (mover datos entre diferentes controles o incluso aplicaciones).

si está intentando arrastrar un artículo desde fuera del contenedor de Silverlight, entonces su mejor opción es revisar silverlight 4 beta

public MainPage()
 {
     InitializeComponent();
     Loaded += new RoutedEventHandler(MainPage_Loaded);   
     // wire up the various Drop events
     InstallButton.Drop += new DragEventHandler(InstallButton_Drop);
     InstallButton.DragOver += new DragEventHandler(InstallButton_DragOver);
     InstallButton.DragEnter += new DragEventHandler(InstallButton_DragEnter);
     InstallButton.DragLeave += new DragEventHandler(InstallButton_DragLeave);
 }

 void InstallButton_Drop(object sender, DragEventArgs e)
 {
     IDataObject foo = e.Data; // do something with data
 }

Esto solía ser tan fácil en VB6. Pero ahora realmente solo tenemos lo que solía llamarse OleDrag.

De todos modos, el siguiente código debería mostrar cómo. Solo necesita una sola etiqueta ( dragDropLabel ) y establezca la propiedad AllowDrop del formulario ( DragDropTestForm ) en True.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DragDropTest
{
    public partial class DragDropTestForm : Form
    {
        // Negative offset to drop location, to adjust for position where a drag starts
        // on a label.
        private Point _labelOffset;

        // Save the full type name for a label, since this is used to test for the control type.
        private string labelTypeName = typeof(Label).FullName;

        public DragDropTestForm()
        {
            InitializeComponent();
        }

        private void dragDropLabel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _labelOffset = new Point(-e.X, -e.Y);
            }
        }

        private void dragDropLabel_MouseMove(object sender, MouseEventArgs e)
        {
            const double minimumDragDistance = 4;
            const double minimumDragDistanceSquared = minimumDragDistance * minimumDragDistance;

            if (e.Button == MouseButtons.Left)
            {
                // Minimum n pixel movement before drag starts.
                if (((Math.Pow(_labelOffset.X - e.X, 2)) + Math.Pow(_labelOffset.Y - e.Y, 2)) >= minimumDragDistanceSquared)
                {
                    dragDropLabel.DoDragDrop(dragDropLabel, DragDropEffects.Move);
                }
            }       
        }

        private void DragDropTestForm_DragOver(object sender, DragEventArgs e)
        {
            IDataObject data = e.Data;

            string[] formats = data.GetFormats();

            if (formats[0] == labelTypeName)
            {
                e.Effect = DragDropEffects.Move;
            }
        }

        private void DragDropTestForm_DragDrop(object sender, DragEventArgs e)
        {
            IDataObject data = e.Data;

            string[] formats = data.GetFormats();

            if (formats[0] == labelTypeName)
            {
                Label label = (Label) data.GetData(formats[0]);
                if (label == dragDropLabel)
                {
                    Point newLocation = new Point(e.X, e.Y);
                    newLocation.Offset(_labelOffset);
                    dragDropLabel.Location = this.PointToClient(newLocation);
                }
            }
        }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top