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; }}报错了
时间: 2024-02-14 16:16:08 浏览: 72
这段代码的报错信息可能是因为 `pictureBox1` 控件的 `ImageLocation` 属性为只读属性,不能直接对其赋值。你可以尝试修改为 `pictureBox1.Location` 属性来实现鼠标拖动图片的效果。
修改后的代码如下:
```
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.Location;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point mousePos = Control.MousePosition;
mousePos.Offset(mouseOffset.X, mouseOffset.Y);
pictureBox1.Location = mousePos;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
mouseOffset = Point.Empty;
imageLocation = Point.Empty;
}
}
```
希望这能帮助到你!
阅读全文