【发布时间】:2016-04-27 19:45:45
【问题描述】:
我想制作一个功能,当用户在面板上单击并拖动光标时,它将显示一个临时突出显示的矩形。而当用户释放他的拖动时,矩形会立即消失。
我知道MouseMove,但它仍然让我感到困惑。我将不胜感激任何帮助。提前谢谢你。
编辑: 好的,我现在找到了MouseMove 的方法,这是我的代码:
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
int x;
int y;
int width;
int height;
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Rectangle ee = new Rectangle(x, y, width, height);
using (Pen pen = new Pen(Color.Red, 2))
{
e.Graphics.DrawRectangle(pen, ee);
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
width = e.X - x;
height = e.Y - y;
pictureBox1.Invalidate();
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
x = e.X;
y = e.Y;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
x = 0;
y = 0;
width = 0;
height = 0;
pictureBox1.Invalidate();
}
}
}
}
但是,当我尝试从右到左或从下到上单击并拖动时,我仍然遇到问题,这将导致矩形的负值。对这件事有什么想法吗?先感谢您。 :)
【问题讨论】:
-
使用面板的 Paint 事件来绘制矩形。通过在鼠标移动时调用其 Invalidate() 方法使其运行。
-
@HansPassant 是的,在我编辑的帖子中,我发现它是这样的,但是当我尝试单击并从右向左或从底部拖动到顶部,这将导致矩形的负值。
-
@NullException 我认为这是另一种情况。不过还是谢谢:)
标签: c# winforms panel highlight