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

C#Winform接受拖放文件

C#2个月前 (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://www.pythonopen.com/?id=7936

相关文章

ListView RetrieveVirtualListItem 事件需要每个 ListView 列的列表视图子项。”

System.InvalidOperationException:“处于 VirtualMode 中...

C# decimal

概述在 C# 中,decimal是一种数据类型,用于表示高精度的十进制数值。它主要用于需要精确计算的...

C# 类接口

定义接口是一种抽象类型,它定义了一组方法签名(方法名称、参数列表和返回类型),但没有方法体。接口用于...

C# ref 和out

ref关键字概念:ref是 C# 中的一个关键字,用于按引用传递参数。当在方法调用中使用ref关键字...

C# Byte[]转为Image

以下是在 C# 中将byte[](字节数组,通常表示图像的二进制数据)转换为Image类型的常见方法...