C# .NET

Panel내부에서 Control 위치변경 ( Drag & Drop )

Code GGOON 2019. 12. 11. 10:26
반응형

Sample로 WindowsForm에 Panel 하나와 PictureBox 3개 (Control) 를 배치하여 테스트 함.

    public partial class Form1 : Form
    {
        Random rnd = new Random();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.panel1.AllowDrop = true;
            
            foreach(Control c in this.panel1.Controls)
            {
                c.MouseDown += new MouseEventHandler(C_MouseDown);
            }

            this.panel1.DragOver += new DragEventHandler(panel1_DragOver);
            this.panel1.DragDrop += new DragEventHandler(panel1_DragDrop);
        }

        void C_MouseDown(object sender, MouseEventArgs e)
        {
            Control c = sender as Control;
            c.DoDragDrop(c, DragDropEffects.Move);
        }

        void panel1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        void panel1_DragDrop(object sender, DragEventArgs e)
        {
            Control c = e.Data.GetData(e.Data.GetFormats()[0]) as Control;

            if (c != null)
            {                
                c.Location = this.panel1.PointToClient(new Point(e.X, e.Y));
            }
        }
    }

 

 

Form Load 화면
Contorl DrogDrop 테스트 화면

반응형