C#TextBox控件拖拽實現獲得文件路徑,雙擊選擇文件夾


步驟:

1、 通過DragEnter事件獲得被拖入窗口的“信息”(可以是若干文件,一些文字等等),在DragDrop事件中對“信息”進行解析。
2、接受拖放控件的AllowDrop屬性必須設置成true;
3、必須在DragEnter事件中設置好要接受拖放的效果,默認為無效果。(所以單獨寫DragDrop事件是不會具有拖拽功能的)

 

private void textBox1_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effect = DragDropEffects.Link;
        this.textBox1.Cursor = System.Windows.Forms.Cursors.Arrow;  //指定鼠標形狀(更好看)  
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}

private void textBox1_DragDrop(object sender, DragEventArgs e)
{
     //GetValue(0) 為第1個文件全路徑
     //DataFormats 數據的格式,下有多個靜態屬性都為string型,除FileDrop格式外還有Bitmap,Text,WaveAudio等格式
     string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
    textBox1.Text = path;
    this.textBox1.Cursor = System.Windows.Forms.Cursors.IBeam; //還原鼠標形狀
}

 

txt_RootPath.AllowDrop = true;
txt_RootPath.DragEnter += Txt_RootPath_DragEnter;
txt_RootPath.DragDrop += Txt_RootPath_DragDrop;
txt_RootPath.DoubleClick += Txt_RootPath_DoubleClick;

 

private void Txt_RootPath_DoubleClick(object sender, EventArgs e)
{

    FolderBrowserDialog openFileDialog = new FolderBrowserDialog();
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        (sender as TextBox).Text = openFileDialog.SelectedPath;
        this.LoadProject();
    }
}

private void Txt_RootPath_DragDrop(object sender, DragEventArgs e)
{
    string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
    (sender as TextBox).Text = path;
    (sender as TextBox).Cursor = System.Windows.Forms.Cursors.IBeam; //還原鼠標形狀
    this.LoadProject();
}

private void Txt_RootPath_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effect = DragDropEffects.Link;
        (sender as Control).Cursor = System.Windows.Forms.Cursors.Arrow;  //指定鼠標形狀(更好看)  
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM