Click here to Skip to main content
15,908,907 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
C#
CreateGraphic.DrawRectangle(pen,rectangle);
Posted
Updated 27-Dec-11 20:44pm
v2

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:
C#
private bool drawBox = false;
private Point start;
private Point end;
Handle the Paint event:
C#
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:

C#
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;
    }
 
Share this answer
 
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 ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900