Skip to main content
 首页 » 编程设计

Winforms DragDrop 的 C# DragEnter 事件

2024年02月24日18me-sa

为什么我们实际上需要处理放置目的地的 DragEnter 事件?

它在目的地的作用是什么?

源头

public partial class ToolBoxForm : System.Windows.Forms.Form 
    { 
        public ToolBoxForm() 
        { 
            InitializeComponent(); 
        } 
 
        private void lbl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) 
        { 
            Label lbl = (Label)sender; 
            lbl.DoDragDrop(lbl.Image, DragDropEffects.Link); 
        } 
    } 

在目的地:

public partial class DrawingArea : Form 
    { 
        public DrawingArea() 
        { 
            InitializeComponent(); 
        } 
 
        private void DrawingArea_Load(object sender, System.EventArgs e) 
        { 
            ToolBoxForm toolBoxForm = new ToolBoxForm(); 
            this.AddOwnedForm(toolBoxForm); 
            toolBoxForm.Show(); 
 
            pictureBox1.AllowDrop = true; 
        } 
 
        private void picDrawingArea_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) 
        { 
            if (e.Data.GetDataPresent(DataFormats.Bitmap)) 
            { 
                e.Effect = DragDropEffects.Copy;                 
            } 
            else 
            { 
                e.Effect = DragDropEffects.None; 
            } 
        } 
 
        private void picDrawingArea_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) 
        { 
            Graphics g = pictureBox1.CreateGraphics(); 
            g.DrawImage((Image)e.Data.GetData(DataFormats.Bitmap), new Point(e.X - this.Left - 12, e.Y - this.Top - 30)); 
        } 
    } 

当我注释掉代码时:

if (e.Data.GetDataPresent(DataFormats.Bitmap)) 
                { 
                    e.Effect = DragDropEffects.Copy;                 
                } 
                else 
                { 
                    e.Effect = DragDropEffects.None; 
                } 

图像没有被丢弃。

请您参考如下方法:

从到DragDropEffects MSDN Page :

Member
name
Description
None The drop target does not accept the data.
Copy The data from the drag source is copied to the drop target.
Move The data from the drag source is moved to the drop target.
Link The data from the drag source is linked to the drop target.
Scroll The target can be scrolled while dragging to locate a drop position that is not currently visible in the target.
All The combination of the Copy, Move, and Scroll effects.

因此,如果您想接受掉落,则必须将其设置为 None 以外的值。

但是,下一句话让我相信它只是用于反馈:

You can use DragDropEffects to display different mouse pointers for drag-and-drop operations. For example, you can display a plus symbol for a Copy drag-and-drop operation, an arrow symbol for a Move drag-and-drop operation, or a red circle with a line through it symbol for a None drag-and-drop operation.