C#中实现拖拽功能,补全中

简单的图片拖拽

  在这个例子中我们将一个PictureBox中的图片拖拽到另一个PictureBox中

  在WinForm窗体中有两个PictureBox;分别为pictureBox1和pictureBox2

  首先我们要把你想接受拖放功能的控件的AllowDrop功能打开,因为PictureBox默认的AllowDrop属性是隐藏,所以我们要用它的上一级来打开AllowDrop属性

  public Form1()
        {
            InitializeComponent();
            Control c = pictureBox2;
            c.AllowDrop = true;
        }

  在拖拽功能中我们主要使用的事件就是MouseDown、DragEnter和DragDrop

  接下来我们要设置pictureBox1的MouseDown事件,当鼠标按下时发生

 private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            this.pictureBox1.DoDragDrop(pictureBox1.Image, DragDropEffects.Copy);
        }

  DoDragDrop是开始执行拖放操作

  设置pictureBox2的DragEnter事件,当鼠标拖拽并进入到pictureBox的工作区时发生

  private void pictureBox2_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Bitmap))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else e.Effect = DragDropEffects.None;
        }

  e.Data.GetDataPresent(string format)是用来验证数据是否与指定格式关联,或是否可以转换为指定格式

  Effect属性是拖放操作中目标的放置效果

  设置pictureBox2的DragDrop事件,完成拖拽时发生

private void pictureBox2_DragDrop(object sender, DragEventArgs e)
        {
 
this.pictureBox2.Image=e.Data.GetData(DataFormats.Bitmap) as Image; }

  e.Data.GetData(string format)方法我们用来获取与指定格式关联的数据,参数是指定的格式

  这样我们就把pictureBox1拖到了pictureBox2中

posted @ 2013-05-08 10:16  FightChicken  阅读(759)  评论(0编辑  收藏  举报