Jimmy Inside

www.jimmyzha.com

导航

vs.NET 里面实现文件的拖放

Posted on 2004-08-27 18:02  抱抱龙  阅读(1270)  评论(3编辑  收藏  举报

    最近自己在写一个网络硬盘的Demo,功能上差不多都完成了,不过卡在对文件的拖进拖出了,就好像winamp那样可以从资源管理器等外部拖放歌曲进来,以及能够往外拖放文件。
    于是四处找文章代码,包括比较流行的 使用win32 的几个API的方法(DragAcceptFiles,DragQueryFile,DragFinish)原文请见http://tech.ccidnet.com/pub/article/c1138_a39064_p1.html
    但是在VS.NET里面用C#实现起来都有些问题,拖动文件进来之后却触发不了时间,我把所有的msg show出来都没有WM_DROPFILES = 233这个文件拖放消息。找了很久MSDN也没有得到解决。
    偶然中翻到VS.NET中的MSDN帮助,居然搞定了从外拖进文件,其实是很简单的。。。设定需要接受拖放的AllowDrag = true, 然后设置其DragDrop以及DragEnter事件即可,代码如下



        private void lvwListing_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        
{
            
// Handle FileDrop data.
            if(e.Data.GetDataPresent(DataFormats.FileDrop) )
            
{
                
// Assign the file names to a string array, in 
                
// case the user has selected multiple files.
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                           
                
for (int i=0;i<files.Length ;++i)
                
{

                    Debug.WriteLine(files[i]);
                    
try
                    
{
                        
if (!Directory.Exists(files[i]))
                        
{
                            DoStoreFile(files[i]);
                        }

                        
else
                        
{
                            Debug.WriteLine(
"This is a DIR: " + files[i]);
                        }

                    }

                    
catch(Exception ex)
                    
{
                        MessageBox.Show(ex.Message);
                        
return;
                    }

                }


        
            }

        }


        
private void lvwListing_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        
{
            
// If the data is a file or a bitmap, display the copy cursor.
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) 
            
{
                e.Effect 
= DragDropEffects.Copy;
            }

            
else
            
{
                e.Effect 
= DragDropEffects.None;
            }

        }

     这样就可以接受到外部拖放进来的消息列表了。通过一些简单的处理就可以得到文件列表,搞定。

     不过怎么往外拖文件现在还在找办法,因为网络硬盘也需要通过拖放出去到文件夹来方便下载啊,俺继续找找方法吧