C# 实现通过拖动文件到 程序图标 可执行对此文件的处理

2,036 阅读1分钟
实现通过拖动文件到 程序图标 可执行对此文件的处理,简单方便


方法一: 将文件拖入到程序图标执行

在WinForm 中,需要在入口函数修改,如下

    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                MessageBox.Show("打开 文件 " + string.Join(",", args));
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

此时编译运行,将任意文件拖放到程序图标上就会触发弹出框了,接下来自由发挥,对特定的文件的处理...


方法二: 将文件都拖入窗口执行:

如果要实现,在打开程序窗口后, 将多个文件都一起拖入窗口来做批量处理, 实现几个步骤如下:

在窗口设计中,选择窗口属性,将属性AllowDrag 设置为true,然后

在实现的窗口Form代码中添加两个拖动事件:

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

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var rs = (string[])e.Data.GetData(DataFormats.FileDrop);
                MessageBox.Show("拖入的文件:" + string.Join("\n", rs));
            }
        }

此时编译运行打开,将任意文件都拖入到窗口,就会弹出提示了,接下来自由发挥吧.


附上参考来源:

1. C# WinForm中 怎样把文件拖入程序图标后即打开程序并用程序中的函数打开文件 点这

2. C# WinForm拖入文件到窗体,得到文件路径 点这