1
votes

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:

enter image description here

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?

2
Don't do that. Instead, handle the Paint event and redraw everything.SLaks
@SLaks, Thank you, but I don't understand. If I handle the Paint event of the Form or Panel, how will it know when I want to drag, if there is no MouseDown/MouseMove events?0550
Call Invalidate() to force a repaint.SLaks
@SLaks also, How will I draw a Rectangle and control how it will move with the mouse when you do no have access to e.X or e.Location from within the panel1_Pain() method?0550
Your screenshot is of a control you already have in the toolbox. It is a ListView, no effort is required at all to get it to select items like this, it is automatic. If you are not actually using a ListView then you need to be explicit about what an "item" on the panel looks like. It gets to be a lot harder if they are actually controls, that requires an overlay. Another window that displays the rectangle on top of the existing controls. I wrote one here.Hans Passant

2 Answers

0
votes

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

filled rubber band in Winforms Application

-1
votes

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

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