C# WinForm 將內容拖曳至外部 示範

在上一篇 C# 將內容、檔案拖曳至 WinForm 應用程式中 教學 介紹了將外部內容拖曳至 WinForm 中的方式,那能不能將 WinForm 內的檔案拖曳至外部呢?

拖曳文字

拖曳文字非常簡單,這裡我們動態產生一個 Label ,在滑鼠點擊時設定拖曳的資料為 Label 的文字。這樣我們使用滑鼠左鍵按住 Label 並拖曳到支援拖曳輸入文字的地方(例如 Word, 瀏覽器搜尋框等)並放開就會出現該文字。
    
Label label = new(); // 動態產生 Label
label.Text = "Text123";
label.Location = new Point(10, 50);
this.Controls.Add(label); // 將 Label 加入到 Form 中 (讓它顯示在畫面上)

label.MouseDown += (sender, e) =>
{
    if (e.Button == MouseButtons.Left) // 滑鼠左鍵按下時
    {
        // 設定拖曳的資料內容為 Label 的文字
        label.DoDragDrop(label.Text, DragDropEffects.Copy);
    }
};
    

拖曳檔案

其實並不是直接拖曳檔案,而是檔案的路徑,並說明這個是檔案。在拖曳 Label 這個檔案路徑時,就會讓外部知道這個是檔案,自己去實際路徑把檔案取出。直接看程式碼:
    
Label label = new Label();
label.AutoSize = true;
label.Text = @"C:\Users\ruyut\Pictures\ruyut.png";
label.Location = new Point(20, 40);
this.Controls.Add(label);

label.MouseDown += (sender, e) =>
{
    if (e.Button == MouseButtons.Left)
    {
        string filePath = label.Text;
        if (File.Exists(filePath))
        {
            string[] fileNames = { filePath };
            DataObject dataObject = new DataObject(DataFormats.FileDrop, fileNames);
            label.DoDragDrop(dataObject, DragDropEffects.Copy);
        }
    }
};
    

留言