CS 拖动窗体控件代码

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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        bool tuodong = false;//全局变量用于控制是否开始拖动 
        //按钮的MouseDown事件 
        private void button3_MouseDown(object sender, MouseEventArgs e)
        {
            Point p = this.PointToClient(Cursor.Position);
            button3.Location = new Point(p.X - button3.Width / 2, p.Y - button3.Height / 2);
            tuodong = true;
        }
        //按钮的MouseMove事件 
        private void button3_MouseMove(object sender, MouseEventArgs e)
        {
            if (tuodong)
            {
                Point p = this.PointToClient(Cursor.Position);
                button3.Location = new Point(p.X - button3.Width / 2, p.Y - button3.Height / 2);
            }
        }
        //按钮的MouseUp事件 
        private void button3_MouseUp(object sender, MouseEventArgs e)
        {
            tuodong = false;
        }
    }
}
posted @ 2011-07-26 12:33  梦想(胡大利)  阅读(248)  评论(0编辑  收藏  举报