[讀書筆記] Stephens' C# Programming with Visual Studio 2010 24-Hour Trainer 第三十三章

  • 1373
  • 0

閱讀Stephens' C#教材第三十三章筆記 介紹如何做出Drag and Drop的功能

 

Chapter 33 Providing Drag and Drop
 
在某些情境,拖放(Drag and Drop)與剪接簿(Clipboard)的功能有些類似,兩者都是可將資料由一處轉移到另一處,所不同的是,剪接簿會先保留資
 
料直到貼上指令出現才轉移資料,而拖放卻是直接轉移資料。本章討論如何透過拖放(Drag and Drop)與其他的應用程式互動。詳細資料可參考微軟網
 
頁http://msdn.microsoft.com/zh-tw/library/ms742859(v=vs.100).aspx
 
作者強調本章介紹只適用Windows From環境,其他的環境不一定適用,例如ASP.NET的網頁,其拖放觀念與本章內容不同。
 
拖放操作有兩個重要的基本觀念:Drag source(拖曳來源)、Drop target(置放目標)
 
為了有效進行拖曳,平台提供一些重要的Drag source(拖曳來源)事件,例如:GiveFeedback、QueryContinueDrag。
 
重要的Drop target(置放目標)事件,例如: DragEnter、DragLeave、DragOver、DragDrop等。
詳細資料可參考微軟網頁
http://msdn.microsoft.com/zh-tw/library/ms742859(v=vs.100).aspx#Drag_and_Drop_Events
 
開始拖曳第一步是建立一個DataObject類別的實例指向被拖曳的資料並保留該資料內容,這可以透過DoDrag方法進行。
 
DragSource程式示範如何撰寫上述的程式碼。
 

        // Start a drag.
        private void dragLabel_MouseDown(object sender, MouseEventArgs e)
        {
            // If it's not the right mouse button, do nothing.
            if (e.Button != MouseButtons.Right) return;

            // Make the data object.
            DataObject data = new DataObject(DataFormats.Text, dragLabel.Text);

            // Start the drag allowing only copy.
            dragLabel.DoDragDrop(data, DragDropEffects.Copy);
        }
在進行Drop置放之前,目標表單必須將AllowDrop屬性設為True,否則將無法置入資料。
置放目標還必須在DragEnter與DragDrop事件中撰寫程式,讓資料順利置入
 
DropTarget程式示範如何撰寫上述的程式碼。
 

        // A drag entered. List available formats.
        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            // Allow text data.
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                // Only allow the Copy operation.
                e.Effect = DragDropEffects.Copy;
            }
        }

        // Accept dropped data.
        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            // Get the dropped data.
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                dropLabel.Text = (string)e.Data.GetData(DataFormats.Text);

                // Indicate that we copied.
                e.Effect = DragDropEffects.Copy;
            }
        }
 
TRY IT中示範上面兩隻程式的撰寫過程。