通过鼠标任意拖动.NET Winform窗体中的控件

如果你想要实现winform picbox通过鼠标左键拖动图片,但不想拖动控件本身,可以按照以下步骤进行: 1. 在窗体上添加一个PictureBox控件,并设置其SizeMode属性为AutoSize,以自适应图片大小。 2. 在PictureBox的MouseDown事件,判断鼠标左键是否按下,如果是,则记录下鼠标的位置和图片的位置。 3. 在PictureBox的MouseMove事件,判断鼠标左键是否按下,如果是,则计算鼠标移动的距离,并将图片的位置加上这个距离,实现拖动效果。 4. 在PictureBox的MouseUp事件,将记录的位置信息清空,以便下一次拖动。 以下是示例代码: ```csharp public partial class Form1 : Form { private Point mouseOffset; // 鼠标位置与图片位置的差值 private Point imageLocation; // 图片的位置 public Form1() { InitializeComponent(); } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { mouseOffset = new Point(-e.X, -e.Y); imageLocation = pictureBox1.ImageLocation; } } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point mousePos = Control.MousePosition; mousePos.Offset(mouseOffset.X, mouseOffset.Y); pictureBox1.ImageLocation = imageLocation; pictureBox1.ImageLocation = mousePos; } } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { mouseOffset = Point.Empty; imageLocation = Point.Empty; } } ``` 这样,就可以通过鼠标左键拖动图片,而不会拖动控件本身。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值