白夜典雅

夜空的協奏曲

导航

Winform窗体文本框实现拖拽获得目录或文件路径(C#)

经常会用到的东西呢。就先记录下来吧。

这代码其实可以写的更加精简。

不过既然都写出来了。就不重新修饰了。

 

#region AllowDrop        
protected void SetAllTextBox()
        {
            foreach (Control txt in this.Controls)
            {
                if (txt is TextBox)
                {
                    txt.AllowDrop = true;
                    txt.DragDrop += new DragEventHandler(txt_ObjDragDrop);
                    txt.DragEnter += new DragEventHandler(txt_ObjDragEnter);
                }
                else
                {
                    if (txt.Controls.Count > 0)
                    {
                        SetAllTextBox(txt);
                    }
                }
            }


        }

        protected void SetAllTextBox(Control org)
        {
            foreach (Control txt in org.Controls)
            {
                if (txt is TextBox)
                {
                    txt.AllowDrop = true;
                    txt.DragDrop += new DragEventHandler(txt_ObjDragDrop);
                    txt.DragEnter += new DragEventHandler(txt_ObjDragEnter);
                }
                else
                {
                    if (txt.Controls.Count > 0)
                    {
                        SetAllTextBox(txt);
                    }
                }
            }
        }

        private void txt_ObjDragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Link;
        }

        private void txt_ObjDragDrop(object sender, DragEventArgs e)
        {
            ((TextBox)sender).Text
                = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
        }
        #endregion

 

posted on 2011-12-15 10:20  鹰夜八百  阅读(1422)  评论(0)    收藏  举报