c#如何用鼠标中键拖动picturebox图片或图形?想CAD那样一直按着中键然后拖动图片
发布网友
发布时间:2022-04-26 00:37
我来回答
共1个回答
热心网友
时间:2023-10-25 10:20
1)在Form1上布置一个PictureBox,在pictureBox1中加载一个合适的图片。然后,对pictureBox1的事件:MouseDown、MouseUp和MouseMove编程,见下面的代码
2)Form1.cs
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Point p0;
bool canDrag;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Middle)
{
// 按下鼠标中键,记录鼠标按下的位置
p0 = e.Location;
// 设置标志:准备拖动图片
canDrag= true;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Middle)
{
// 松开鼠标中键,清除拖动标志,禁止鼠标拖动图标操作
canDrag= false;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (canDrag)
{
// 在图片上按下鼠标中键并移动鼠标,改变图标的位置
pictureBox1.Location =
new Point(pictureBox1.Left + e.X - p0.X, pictureBox1.Top + e.Y - p0.Y);
}
}
}
}