用鼠标左击事件实现移动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);
}
}
}
其中涉及三个概念:
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);
}
}
}
相关文章推荐
- ASP.NET基础教程-DataGrid表格控件-利用ItemDataBound事件实现鼠标移动到控件的某一行时改变该行的背景色
- ArcEngine中实现axMapControl控件鼠标左击右击响应不同事件
- WinForm 鼠标进入移开窗体事件,因子控件导致的误触发
- winform实现限制及解除鼠标移动范围的方法
- java实现控件的移动及使用鼠标改变控件大小
- C#无边框窗体移动 将事件绑定到想实现的控件上
- [转] WinForm实现移除控件某个事件的方法
- 老土但有效的刷百度空间人气不被封的方法(C#实现操纵鼠标事件,单击、移动、滚轮)
- 移动控件位置和多次点击事件的源码实现
- 让Shockwave flash控件响应鼠标移动的事件
- MFC实现STATIC TEXT控件的鼠标事件解决方案
- C#计时器;控件移动;获取鼠标坐标;事件调用事件;
- 控制WinForm控件上的键盘,鼠标事件响应
- MFC:为STATIC控件添加鼠标移动事件(VS2010)
- JS实现控件跟随鼠标移动
- 使用layout方法实现控件的移动并且不影响点击事件
- 实现让一个控件跟着鼠标一起移动? vb.net
- 通过监听Windows消息实现控件的键盘和鼠标事件路由
- Android基于hover组件实现监控鼠标移动事件的方法
- cocos2d-x window实现鼠标移动 键盘事件