当前位置:首页 > 开发 > C# > 正文内容

C#Winform接受拖放文件

C#8个月前 (01-10)
        public Form1()
        {
            InitializeComponent();

            this.AllowDrop = true; // 关键步骤1:允许窗体接受拖放
            this.DragEnter += new DragEventHandler(MainForm_DragEnter);
            this.DragDrop += new DragEventHandler(MainForm_DragDrop);
        }

        private void MainForm_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))// 关键步骤2:检查拖入的是否是文件
            {
                e.Effect = DragDropEffects.Copy; // 设置鼠标为“复制”效果
            }
        }

        private void MainForm_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);// 关键步骤3:用户松开鼠标后,获取文件路径
            foreach (string file in files)
            {
                Console.WriteLine(file);
            }
        }


Lambda形式

public Form1()
{
    InitializeComponent();

    this.AllowDrop = true; // 关键步骤1:允许窗体接受拖放
    this.DragEnter += (sender, e) =>
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop)) // 关键步骤2:检查拖入的是否是文件
            e.Effect = DragDropEffects.Copy; // 设置鼠标为"复制"效果
    };
    this.DragDrop += (sender, e) =>
    {
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); // 关键步骤3:用户松开鼠标后,获取文件路径
        foreach (string file in files)
        {
            Console.WriteLine(file);
        }
    };
}


转载请注明出处。

本文链接:http://pythonopen.com/?id=7936

相关文章

C# 捕获鼠标

方式一-API    /// <summary>...

在 C# 中实现类似于 Windows 资源管理器的“名称”排序方式

要在 C# 中实现类似于 Windows 资源管理器的“名称”排序方式,你需要考虑以下几点:1. 不...

C# BackgroundWorker

1.概述BackgroundWorker是一个在 WinForms 应用程序中用于简化在后台线程执行...

C# System.IO.Path

System.IO.Path.GetExtension返回指定的路径字符串的扩展名。string&n...

C# Byte[]转为Bitmap

在 C# 中,可以使用System.Drawing命名空间下的相关类将byte[]类型的数据转换为B...

C# TextRenderer.MeasureText

TextRenderer.MeasureText是System.Windows.Forms命名空间中...