拖拽生成控制元件副本
阿新 • • 發佈:2018-11-27
public class Form1 { //計數變數,說明輸出了第N個Button private int count = 1; private void Form1_Load(System.Object sender, System.EventArgs e) { //窗體自身支援接受拖拽來的控制元件 this.AllowDrop = true; } private void Button1_MouseDown(System.Object sender, System.Windows.Forms.MouseEventArgs e) {//左鍵的話,標誌位為true(表示拖拽開始) if ((e.Button == System.Windows.Forms.MouseButtons.Left)) { Button1.DoDragDrop(Button1, DragDropEffects.Copy | DragDropEffects.Move); //形成拖拽效果,移動+拷貝的組合效果 } } private void Form1_DragEnter(System.Object sender, System.Windows.Forms.DragEventArgs e) {//當Button被拖拽到WinForm上時候,滑鼠效果出現 if ((e.Data.GetDataPresent(typeof(Button)))) { e.Effect = DragDropEffects.Copy; } } private void Form1_DragDrop(System.Object sender, System.Windows.Forms.DragEventArgs e) { //拖放完畢之後,自動生成新控制元件 Button btn = newButton(); btn.Size = Button1.Size; btn.Location = this.PointToClient(new Point(e.X, e.Y)); //用這個方法計算出客戶端容器介面的X,Y座標。否則直接使用X,Y是螢幕座標 this.Controls.Add(btn); btn.Text = "按鈕" + count.ToString(); count = count + 1; } public Form1() { DragDrop += Form1_DragDrop; DragEnter += Form1_DragEnter; Load += Form1_Load; } }