Using System.Drawing.DrawRectangle to draw Selection Rectangle to select things

I have a Windows Forms application and need to be able to select objects on the form, in the same way that you select files on the Desktop by left-clicking and dragging over the files, like below:

在这里输入图像描述

I have the following code which I've written by myself, but it's terrible. It's not right. I'm not too worried about the "selection" part of it right now, I'm mainly concerned with how do I draw like this?

private void splitContainer1_Panel1_MouseMove(object sender, MouseEventArgs e)
{
    if (mouseDown)
    {
        // TODO: Draw Rectangle (so you can select elements on the canvas).


        Graphics graphics = Graphics.FromHwnd(splitContainer1.Panel1.Handle);
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        Pen pen = new Pen(Color.SlateBlue, 0.5f);

        graphics.PageUnit = GraphicsUnit.Pixel;

        graphics.DrawRectangle(pen, e.X, e.Y, (e.Location.X + e.X) - lastCursorLocation.X, (e.Location.Y + e.Y) - lastCursorLocation.Y);
    }
}

Update

private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) { // TODO: Draw Rectangle (so you can select elements on the canvas).

        Graphics graphics = Graphics.FromHwnd(splitContainer1.Panel1.Handle);
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

        Pen pen = new Pen(Color.SlateBlue, 0.5f);

        graphics.PageUnit = GraphicsUnit.Pixel;

        graphics.DrawRectangle(pen, 1, 1, 1, 1);

        Invalidate();
    }

After placing the code in the Paint event, and calling Invalidate(), nothing draws on the form at all. I'm obviously doing something wrong, but what?


Check the following thread. What you are looking for is called a rubber band :

filled rubber band in Winforms Application


I ended up using some code that I found on the Microsoft Connect website:

http://support.microsoft.com/kb/314945

链接地址: http://www.djcxy.com/p/50332.html

上一篇: 为什么我看不到任何选定的项目?

下一篇: 使用System.Drawing.DrawRectangle绘制选择矩形来选择事物