博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# WPF:把文件给我拖进来!!!
阅读量:4033 次
发布时间:2019-05-24

本文共 2256 字,大约阅读时间需要 7 分钟。

  • 首发公众号:Dotnet9

  • 作者:沙漠之尽头的狼

  • 日期:202-11-27

一、本文开始之前

上传文件时,一般是提供一个上传按钮,点击上传,弹出文件(或者目录选择对话框),选择文件(或者目录)后,从对话框对象中取得文件路径后,再进行上传操作。

对话框选择文件

选择对话框代码如下:

OpenFileDialog openFileDialog = new OpenFileDialog();openFileDialog.Title = "选择Exe文件";openFileDialog.Filter = "exe文件|*.exe";openFileDialog.FileName = string.Empty;openFileDialog.FilterIndex = 1;openFileDialog.Multiselect = false;openFileDialog.RestoreDirectory = true;openFileDialog.DefaultExt = "exe";if (openFileDialog.ShowDialog() == false){    return;}string txtFile = openFileDialog.FileName;

但一般来说,对用户体验最好的,应该是直接鼠标拖拽文件了:

百度网盘拖拽上传文件

下面简单说说WPF中文件拖拽的实现方式。

二、WPF中怎样拖拽文件呢?

其实很简单,只要拖拽接受控件(或容器)注册这两个事件即可:DragEnterDrop

先看看我的实现效果:

拖拽文件进QuickApp中

Xaml中注册事件

注册事件:

事件处理方法:

  1. Grid_DragEnter处理方法

private void Grid_DragEnter(object sender, DragEventArgs e){    if (e.Data.GetDataPresent(DataFormats.FileDrop))    {        e.Effects = DragDropEffects.Link;    }    else    {        e.Effects = DragDropEffects.None;    }}

DragDropEffects.Link:处理拖拽文件操作

  1. Grid_Drop处理方法

这是处理实际拖拽操作的方法,得到拖拽的文件路径(如果是操作系统文件快捷方式(扩展名为lnk),则需要使用com组件(不是本文讲解重点,具体看本文开源项目)取得实际文件路径)后,即可处理后续操作(比如文件上传)。

private void Grid_Drop(object sender, DragEventArgs e){    try    {        var fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();        MenuItemInfo menuItem = new MenuItemInfo() { FilePath = fileName };        // 快捷方式需要获取目标文件路径        if (fileName.ToLower().EndsWith("lnk"))        {            WshShell shell = new WshShell();            IWshShortcut wshShortcut = (IWshShortcut)shell.CreateShortcut(fileName);            menuItem.FilePath = wshShortcut.TargetPath;        }        ImageSource imageSource = SystemIcon.GetImageSource(true, menuItem.FilePath);        System.IO.FileInfo file = new System.IO.FileInfo(fileName);        if (string.IsNullOrWhiteSpace(file.Extension))        {            menuItem.Name = file.Name;        }        else        {            menuItem.Name = file.Name.Substring(0, file.Name.Length - file.Extension.Length);        }        menuItem.Type = MenuItemType.Exe;        if (ConfigHelper.AddNewMenuItem(menuItem))        {            AddNewMenuItem(menuItem);        }    }    catch (Exception ex)    {        MessageBox.Show(ex.Message);    }}

三、本文Over

功能很简单,不求精深,会用就行。

转载地址:http://fmkdi.baihongyu.com/

你可能感兴趣的文章
Android系统构架
查看>>
Android 跨应用程序访问窗口知识点总结
查看>>
各种排序算法的分析及java实现
查看>>
SSH框架总结(框架分析+环境搭建+实例源码下载)
查看>>
js弹窗插件
查看>>
自定义 select 下拉框 多选插件
查看>>
js判断数组内是否有重复值
查看>>
js获取url链接携带的参数值
查看>>
gdb 调试core dump
查看>>
gdb debug tips
查看>>
arm linux 生成火焰图
查看>>
jtag dump内存数据
查看>>
linux和windows内存布局验证
查看>>
linux config
查看>>
linux insmod error -1 required key invalid
查看>>
linux kconfig配置
查看>>
linux不同模块completion通信
查看>>
linux printf获得时间戳
查看>>
C语言位扩展
查看>>
linux dump_backtrace
查看>>