C#设置一个控件可以鼠标拖动
C#设置一个控件可以鼠标拖动:
新建一个C#项目,
创建一个label控件,
设置label的鼠标按下和抬起事件分别为:label1_MouseDown和label1_MouseUp。
对代码进行如下修改。
public partial class Form1 : Form { private Point mouse_offset; public Form1() { InitializeComponent(); } private void label1_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point mousePos = Control.MousePosition; mousePos.Offset(mouse_offset.X, mouse_offset.Y); ((Control)sender).Location = ((Control)sender).Parent.PointToClient(mousePos); } } private void label1_MouseDown(object sender, MouseEventArgs e) { mouse_offset = new Point(-e.X, -e.Y); } }
运行后,就可以拖动label随处移动啦。
相关推荐
chensen 2020-11-14
leihui00 2020-09-16
二十不悔三十而立 2020-08-19
shining0 2020-08-02
TyrionZK 2020-07-26
TreasureZ 2020-07-26
natloc 2020-07-19
Bonrui编程路 2020-07-18
TyrionZK 2020-07-18
TyrionZK 2020-07-04
TreasureZ 2020-06-25
TreasureZ 2020-06-20
TreasureZ 2020-06-16
jameszgw 2020-06-14
Bonrui编程路 2020-06-13
Bonrui编程路 2020-06-07