webbrowser 实现拖拽文件,webbrowser drop files,Webbrowser control drag drop Multiple Files
微软并没有提供webbrowser 实现拖拽文件的支持,默认拖拽文件到webbrowser 是通过Navigating触发文件下载,虽然可以通过Navigating获取到拖拽的文件,但是只能获取到单个文件,如果是多个文件拖拽就无法获取。
下载这个类可以实现webbrowser对多个文件拖拽的支持:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace UploadImages { public partial class MyWebBrowser : WebBrowser { private const int WmDropfiles = 0x233; [DllImport("shell32.dll")] private static extern uint DragQueryFile(IntPtr hDrop, uint iFile, StringBuilder lpszFile, uint cch); [DllImport("shell32.dll")] private static extern void DragAcceptFiles(IntPtr hWnd, bool fAccept); [DllImport("shell32.dll")] private static extern void DragFinish(IntPtr hDrop); protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); //指示接受文件拖放操作 if (!DesignMode) { DragAcceptFiles(Handle, true); } } protected override void WndProc(ref Message m) { if (m.Msg == WmDropfiles) { #region 解析消息 //获取拖放的文件数量 var count = DragQueryFile(m.WParam, 0xffffffff, null, 0); //解析所有播放的文件路径 var filePaths = new string[count]; for (uint i = 0; i < count; i++) { var sb = new StringBuilder(1024); DragQueryFile(m.WParam, i, sb, 1024); filePaths[i] = sb.ToString(); } DragFinish(m.WParam); #endregion //是否继续触发之后的消息处理 var isCancel = false; #region 触发自定义文件拖放事件 if (DragFile != null) { var args = new DragFileEventArgs(filePaths); DragFile(this, args); isCancel = args.IsCancel; } #endregion if (isCancel) return; } base.WndProc(ref m); } public event EventHandler<DragFileEventArgs> DragFile; public class DragFileEventArgs : EventArgs { private readonly string[] _filePaths; public bool IsCancel { get; set; } public DragFileEventArgs(string[] filePaths) { _filePaths = filePaths; } public string[] FilePaths { get { return _filePaths; } } } } }
使用方法:
MyWebBrowser webBrowser1 = new MyWebBrowser();
webBrowser1.AllowNavigation = false; webBrowser1.AllowWebBrowserDrop = false; webBrowser1.DragFile += (object sender, MyWebBrowser.DragFileEventArgs arg) => { string[] fps = arg.FilePaths; arg.IsCancel = true; };