C#如何像在Windows资源管理器中一样在面板上绘制橡皮筋选择矩形? [英] C# How to Draw a Rubber Band Selection Rectangle on Panel, like one used in Windows Explorer?
问题描述
我有一个Flow Layout Panel,其中包含一些用户控件.我想使用鼠标使用矩形选择来选择这些控件,就像在Windows文件浏览器中使用的那样.我已经尝试过这些操作: https://support.microsoft.com/en-us/kb/314945 但这是非常闪烁的,没有用(我可能是错的,请纠正我).请提供任何好的示例.
I have one Flow Layout Panel with some User Controls in it. I Want to Select these controls using rectangle selection using Mouse,like one used in windows file explorer . I have tried these : https://support.microsoft.com/en-us/kb/314945 But it was very flickering and not useful (I might be wrong,please correct me). Any good examples please.
推荐答案
绘制橡皮筋矩形是这样的:
Drawing the rubber-band rectangle is done like this:
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
panel1.Refresh();
using (Graphics g = panel4.CreateGraphics())
{
Rectangle rect = GetRectangle(mdown, e.Location);
g.DrawRectangle(Pens.Red, rect);
}
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mdown = e.Location;
}
它使用辅助功能:
static public Rectangle GetRectangle(Point p1, Point p2)
{
return new Rectangle(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y),
Math.Abs(p1.X - p2.X), Math.Abs(p1.Y - p2.Y));
}
我没有任何闪烁.如果这样做,也许您已经编码了 Paint
事件,则可能要使用双缓冲的 Panel
:
I don't get any flicker from it. If you do, maybe you have coded the Paint
event, you may want to use a double-buffered Panel
:
class DrawPanel : Panel
{
public DrawPanel()
{
DoubleBuffered = true;
}
}
更新:您可以使用代替
或 Panel
,后者是 Container
控件,并不是真正要使用的控件> Picturebox Label
(带有 Autosize = false
);两者都具有开箱即用的 DoubleBuffered
属性,并且比 Panels
更好地支持绘图.
Update: Instead of a Panel
, which is a Container
control and not really meant to draw onto, you can use a Picturebox
or a Label
(with Autosize=false
); both have the DoubleBuffered
property turned on out of the box and support drawing better than Panels
do.
这篇关于C#如何像在Windows资源管理器中一样在面板上绘制橡皮筋选择矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!