分享

C# 按钮拖动效果

 kingjae 2012-12-08
 C# 按钮拖动效果

1. 创建Windows应用程序

2. 在默认窗口中拖放一个按钮

3. 编辑按钮的MouseDown事件,如下:

Point oriPoint;//定义鼠标按下时候的位置

private void button1_MouseDown(object sender, MouseEventArgs e)

{

oriPoint = e.Location;

}

4. 编辑按钮的MouseMove事件,如下:

private void button1_MouseMove(object sender, MouseEventArgs e)

{

if (e.Button == MouseButtons.Left)//如果按下了鼠标左键

{

Button b = sender as Button;

//当前位置等于鼠标移动前的位置加上和起始位置的差距

b.Location = new Point(b.Location.X + (e.X - oriPoint.X), b.Location.Y + (e.Y - oriPoint.Y));

}

}

下面是拖动按钮和图片实例:

    public partial class Form1 : Form
    {
        Point oriPoint;
        Point picPoint;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            oriPoint = e.Location;
        }
        private void button1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Button b = sender as Button;
                b.Location = new Point(b.Location.X + (e.X - oriPoint.X), b.Location.Y + (e.Y - oriPoint.Y));      
           
            }
          
        }
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            picPoint = e.Location;
        }
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                PictureBox pb=sender as PictureBox;
                pb.Location = new Point(pb.Location.X + (e.X - picPoint.X), pb.Location.Y + (e.Y - picPoint.Y));
            }
        }
        }
  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多