如何通过鼠标从任何坐标通过代码绘制矩形 [英] how to draw a rectangle by mouse through code from any co-ordinates
本文介绍了如何通过鼠标从任何坐标通过代码绘制矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
仅当我从左上角拖动时,我的程序才通过代码绘制矩形.
我希望它可以从任何侧面拖动鼠标.
我正在使用
My program draws rectangle through code only when i drag from upper-left corner.
I want it to be from any side i drag the mouse.
I''m using
CreateGraphic.DrawRectangle(pen,rectangle);
推荐答案
,您需要处理四个事件,要绘制的表单或面板:
You need to handle four events, either for the Form you want to draw on, or a Panel instead:
MouseDown
MouseMove
MouseUp
Paint
声明三个类级别的变量:
Declare three class level variables:
private bool drawBox = false;
private Point start;
private Point end;
处理Paint事件:
Handle the Paint event:
private void myPanel_Paint(object sender, PaintEventArgs e)
{
if (start != null && end != null)
{
int mnX = Math.Min(start.X, end.X);
int mnY = Math.Min(start.Y, end.Y);
int mxX = Math.Max(start.X, end.X);
int mxY = Math.Max(start.Y, end.Y);
e.Graphics.DrawRectangle(Pens.Black, mnX, mnY, mxX - mnX, mxY - mnY);
}
}
并处理鼠标事件:
And handle the mouse events:
private void myPanel_MouseDown(object sender, MouseEventArgs e)
{
drawBox = true;
start = e.Location;
end = start;
myPanel.Invalidate();
}
private void myPanel_MouseMove(object sender, MouseEventArgs e)
{
if (drawBox)
{
end = e.Location;
myPanel.Invalidate();
}
}
private void myPanel_MouseUp(object sender, MouseEventArgs e)
{
drawBox = false;
}
我自己也以类似的方式解决了它.但是现在在绘制时它会闪烁很多.
我重写方法OnPaintBackgound()并将其留空.这样可以避免完全闪烁,但是会禁用表单背景和其他控件.它变得透明.
谁能建议解决方案...
I solved it myself in a similar way.. But now while drawing it flickers a lot..
i override the method OnPaintBackgound() and left it empty. This avoids flickering completely but form background and other controls are disabled.. It becomes transparent.
Can anyone suggest a solution ...
这篇关于如何通过鼠标从任何坐标通过代码绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文