您的位置:首页 > 移动开发 > Objective-C

用鼠标左击事件实现移动WinForm中控件

2011-09-26 19:52 447 查看
本来以为很简单的小代码,查了一下网上的时间方法,真是很多,但是我没有试出来成功的,没办法,自己结合移动窗口的方法,自己实现了通过鼠标左击实现移动控件的方法。

其中涉及三个概念:

1.控件的位置,Location属性,大家都知道

2鼠标的相对窗口的坐标

3鼠标相对控件的坐标

原理很简单,就是一个公式,公式在下面程序中

现在窗口中放一个button就行啦

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 WindowsFormsApplication4

{

    public partial class Form1 : Form

    {

        private int tmpx = 0;

        private int tmpy = 0;

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

        }

        private void button1_MouseDown(object sender, MouseEventArgs e)

        {

            if (e.Button == MouseButtons.Left)

            {

                this.tmpx = e.X;

                this.tmpy = e.Y;

            }

           

        }     

        private void button1_MouseMove(object sender, MouseEventArgs e)

        {

            if(e.Button == MouseButtons.Left)

            this.button1.Location = new System.Drawing.Point(this.button1.Location.X + e.X - this.tmpx, this.button1.Location.Y + e.Y - this.tmpy);

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  winform button object class