WinForm支持拖拽效果

本文介绍了一种在C# WinForms应用程序中通过拖拽操作来自动生成按钮的方法。具体实现包括:使Button控件支持拖拽、响应拖拽事件并在窗体上放置新按钮等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
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 = new Button();
        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;
    }
}
原文地址:http://www.cnblogs.com/ServiceboyNew/archive/2012/04/29/2476154.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值