C#实现在运行窗体中拖拽组件

来源:互联网 发布:mac的ps首选项在哪里 编辑:程序博客网 时间:2024/06/07 19:32

1.首先要把想要拖拽的控件和窗体的AllowDrop属性设置为true

2.添加要拖拽控件的MouseDown事件:

                private void button1_MouseDown(object sender, MouseEventArgs e)
                 {
                              DoDragDrop(button1,DragDropEffects.Move); //DoDragDrop是一个函数
                 }

3.添加窗体Form1的DragDrop事件:

         private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            object data = e.Data.GetData(typeof(Button));
            if (data == button1)
            {
                button1.Top = this.PointToClient(new Point(e.X, e.Y)).Y;
                button1.Left = this.PointToClient(new Point(e.X, e.Y)).X;
            }          
        }

4.添加窗体Form1的DragEnterDragEnter事件:

private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            object data = e.Data.GetData(typeof(Button));
            if (data != null)
            {
                e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

5.运行一下就可以移动Button1这个控件了

原创粉丝点击