[C#.NET][VB.NET] 如何使用拖曳 DoDragDrop 方法 / DoDragDrop 事件
功能需求:使用左鍵拖曳,可達到複製的功能
Step1.設定 Control.AllowDrop 屬性
{
//1.允許控制項使用拖曳
this.textBox1.AllowDrop = true;
this.textBox2.AllowDrop = true;
}
Step2.在 text1Box1.MouseDown 事件 中,
2-1.判斷是否為滑鼠左鍵按下
2-2.選取 text1Box1.Text 的內容
2-3.使用 text1Box1.DoDragDrop 方法 複製資料
private void textBox1_MouseDown(object sender, MouseEventArgs e)
{
//2-1.判斷是否為滑鼠左鍵
if (e.Button==MouseButtons.Left)
{
//2-2.選取資料
this.textBox1.SelectAll();
//2-3.複製選取的資料
this.textBox1.DoDragDrop(textBox1.SelectedText, DragDropEffects.Copy);
//this.textBox1.DoDragDrop(textBox1.SelectedText, DragDropEffects.Move | DragDropEffects.Copy);
}
}
private void textBox2_DragEnter(object sender, DragEventArgs e)
{
//3.用Effext定義拖曳目標
e.Effect = DragDropEffects.Copy;
}
Step4.在 textBox2_DragEnter事件 中,
4-1.用DragEventArgs類別取得資料
4-2.判斷是否有按下Ctrl鍵
private void textBox2_DragDrop(object sender, DragEventArgs e)
{
//4-1.用DragEventArgs類別取得資料
textBox2.Text = e.Data.GetData(DataFormats.Text).ToString();
//4-2.判斷是否有按下Ctrl鍵
if ((e.KeyState & 8) !=8)
{
this.textBox2.Text = "";
}
}
範例下載:
若有謬誤,煩請告知,新手發帖請多包涵

Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

