20150506—WinForm自动生成按钮&按钮拖动

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace xiaojian2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.splitContainer1.Panel2.Controls.Clear();
            for (int i = 0; i < 100; i++)
            {
                //Form1 xx = new Form1();
                //xx.Show();
                Button btn = new Button() { Name = "btn" + i, Text = "Test" + i, Size = new Size(50, 50) };
                btn.Location = new Point(50 * (i % 10), 50 * (i / 10));
                btn.MouseDown += button1_MouseDown;
                btn.MouseMove += button1_MouseMove;
                this.splitContainer1.Panel2.Controls.Add(btn); //向前台页面添加生成的按钮,
            }

        }
        Point pt;
        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            pt = Cursor.Position;
        }
        private void button1_MouseMove(object sender, MouseEventArgs e)
        {
            
            if (MouseButtons == MouseButtons.Left)
            {
                int px = Cursor.Position.X - pt.X;
                int py = Cursor.Position.Y - pt.Y;

                Button butt = (Button)sender;//获取是哪个按钮,并转换

                butt.Location = new Point(butt.Location.X + px, butt.Location.Y + py);
                pt = Cursor.Position;
                
            }
        }
    }
}

image

posted @ 2015-05-06 09:37  Tirisfal  阅读(832)  评论(0编辑  收藏  举报