首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

如创造运行时可以拖拽的控件

2013-03-27 
如创建运行时可以拖拽的控件就像工具箱里的控件那样,是用户在运行程序是可以采用拖拽操作。http://blog.csd

如创建运行时可以拖拽的控件
就像工具箱里的控件那样,是用户在运行程序是可以采用拖拽操作。
http://blog.csdn.net/bobye1230/article/details/4462696
[解决办法]
楼上的方法看起来好麻烦的,
.net中实现拖拽很简单。
比如要在一个form上拖动一个button。


        private Point MouseMaggin;
        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                MouseMaggin = e.Location;
                button1.DoDragDrop(button1, DragDropEffects.Move);
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            //当Button被拖拽到WinForm上时候,出现鼠标效果
            if ((e.Data.GetDataPresent(typeof(Button))))
            {
                e.Effect = DragDropEffects.Move;
            }
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            MoveButton(e);
        }

        private void MoveButton(DragEventArgs e)
        {
            //得到拖放对象中的Button
            Button btn = e.Data.GetData(typeof(Button)) as Button;
            //计算Button相对于From的X,Y坐标。否则直接使用X,Y是屏幕坐标
            Point newLocation = this.PointToClient(new Point(e.X, e.Y));
            newLocation.Offset(0 - MouseMaggin.X, 0 - MouseMaggin.Y);
            btn.Location = newLocation;
        }

        private void Form1_DragOver(object sender, DragEventArgs e)
        {
            Point currentLocation = this.PointToClient(new Point(e.X, e.Y));
            currentLocation.Offset(0 - MouseMaggin.X, 0 - MouseMaggin.Y);


            textBox1.Text = (currentLocation.X + "," + currentLocation.Y);
            MoveButton(e);
        }



要设置Form的AllowDrop=true,然后处理form的几个drop事件即可。

热点排行