首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 拖放技術完整實作指南

     編輯:關於C#

應用場景

在應用程式中,使用者常需將資料從一個控制項拖曳至另一個控制項,此時需使用拖放技術。

開發步驟

  1. 新增一個表單,放置兩個 Label 與兩個 TextBox 控制項,將 TextBox 分別命名為 txtDataTart(目標)與 txtScoure(來源)。
  2. 將 txtDataTart 的 AllowDrop 屬性設為 true。
  3. 撰寫核心程式碼處理拖放事件。

核心程式碼

private void txtDataTart_DragDrop(object sender, DragEventArgs e)
{
    txtDataTart.Text = e.Data.GetData(DataFormats.Text).ToString();
}

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

private void txtScoure_MouseMove(object sender, MouseEventArgs e)
{
    if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        string reportPath = Application.StartupPath.Substring(0, 
            Application.StartupPath.Substring(0,
            Application.StartupPath.LastIndexOf("\\")).LastIndexOf("\\"));
        reportPath += @"\sl3293dwarro.cur";
        MyNoDropCursor = new Cursor(reportPath);
        DragDropEffects dropEffect = this.txtScoure.DoDragDrop(
            this.txtScoure.Text, DragDropEffects.Copy | DragDropEffects.Link);
    }
}

關鍵點解析

  • AllowDrop = true:啟用控制項接受拖放資料的能力。
  • DragEnter 事件:設定 e.Effect 指示允許的拖放效果(如 Copy、Move、Link)。
  • DragDrop 事件:實際執行資料傳遞,從 e.Data 取得資料。
  • DoDragDrop 方法:啟動拖放作業,傳入要拖曳的資料與允許的效果。
  • 自訂游標:可在 MouseMove 中載入 .cur 檔案作為拖曳時的游標。

常見拖放效果列舉

效果說明
Copy複製資料
Move移動資料
Link建立連結
None不允許拖放
All所有效果
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved