Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to draw the Rectangle by mouse dynamically on Form but required results are not there.Means I want to grab the mouse on the form so rectangle can be draw.
Somebody Please help me......
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace rect
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Point startPos;      // mouse-down position
        Point currentPos;    // current mouse position
        bool drawing;        // busy drawing
        List<Rectangle> rectangles = new List<Rectangle>();  // previous rectangles

        private Rectangle getRectangle()
        {
            return new Rectangle(
                Math.Min(startPos.X, currentPos.X),
                Math.Min(startPos.Y, currentPos.Y),
                Math.Abs(startPos.X - currentPos.X),
                Math.Abs(startPos.Y - currentPos.Y));
        }

        private void canevas_MouseDown(object sender, MouseEventArgs e)
        {
            currentPos = startPos = e.Location;
            drawing = true;
        }

        private void canevas_MouseMove(object sender, MouseEventArgs e)
        {
            currentPos = e.Location;
            if (drawing)
                Invalidate();
        }

        private void canevas_MouseUp(object sender, MouseEventArgs e)
        {
            if (drawing)
            {
                drawing = false;
                var rc = getRectangle();
                if (rc.Width > 0 && rc.Height > 0) rectangles.Add(rc);
                Invalidate();
            }
        }

        private void canevas_Paint(object sender, PaintEventArgs e)
        {
            if (rectangles.Count > 0) e.Graphics.DrawRectangles(Pens.Black, rectangles.ToArray());
            if (drawing) e.Graphics.DrawRectangle(Pens.Red, getRectangle());
        }
    
        private void rectangleShape1_Click(object sender, EventArgs e)
        {
            getRectangle();
        }
    }
}
Posted
Updated 28-Apr-13 23:35pm
v2
Comments
Sergey Alexandrovich Kryukov 29-Apr-13 2:40am    
"Not working" is not informative. The general idea looks correct.
—SA
Naeem Ahmed 29-Apr-13 5:10am    
"Not Working" means when I debug my project. Form of application load accurately but drawing of Rectangle do not take place on the form.....
Sergey Alexandrovich Kryukov 29-Apr-13 8:06am    
When asking such questions, you need to show all "+=" operations for all event instances, declaration of "canevas". And, by the way, it would be much better to add handlers to the invocation lists of event instance without the designer, using anonymous delegate syntax (you did not worry to show the auto-generated code):
canevas.Paint += (sender, eventArgs) => { eventArgs.Graphics.Draw... };
And you can debug it all using the breakpoints, etc. The code is quite simple for find out everything...
—SA
Rob Philpott 29-Apr-13 5:56am    
Essentially it looks ok to me. What is 'canevas'? Are the events hooked up correctly? Put breakpoints in to confirm the mouse events are being received. Put a breakpoint on the Paint method and inspect what getRectangle gives you....
lukeer 29-Apr-13 5:59am    
Does canevas_Paint ever get called?
If so, what data is present in rectangles?

Add that info to your question using the "Improve question" link.

1 solution

The following code performs what you want to do.

C#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace CodeProject
    {

    // *************************************** class DynamicRectangles
    
    public partial class DynamicRectangles : Form
        {

        Point               current_mouse_position;
        Point               mouse_down_position;
        bool                drawing = false;
        List < Rectangle >  rectangles = new List < Rectangle > ( );

        // ***************************************** DynamicRectangles
        
        public DynamicRectangles ( )
            {
            
            InitializeComponent ( );
            }

        // ***************************************** current_rectangle
        
        private Rectangle current_rectangle ( )
            {
            return new Rectangle(
                Math.Min ( mouse_down_position.X, 
                           current_mouse_position.X ),
                Math.Min ( mouse_down_position.Y, 
                           current_mouse_position.Y ),
                Math.Abs ( mouse_down_position.X - 
                           current_mouse_position.X ),
                Math.Abs ( mouse_down_position.Y - 
                           current_mouse_position.Y ) );
            }

        // *********************************************** OnMouseDown
        
        protected override void OnMouseDown ( MouseEventArgs e )
            {
            
            base.OnMouseDown ( e );

            drawing = true;

            current_mouse_position = e.Location;
            mouse_down_position = e.Location;
            }

        // *********************************************** OnMouseMove
        
        protected override void OnMouseMove ( MouseEventArgs e )
            {
            
            base.OnMouseMove ( e );

            current_mouse_position = e.Location;
            if ( drawing )
                {
                Invalidate ( );
                }
            }

        // ************************************************* OnMouseUp
        
        protected override void OnMouseUp ( MouseEventArgs e )
            {
            Rectangle  rectangle;
            base.OnMouseUp ( e );

            drawing = false;

            rectangle = current_rectangle ( );
            if ( ( rectangle.Width > 0 ) && ( rectangle.Height > 0 ) )
                {
                rectangles.Add ( rectangle );
                }
            Invalidate ( );
            }

        // *************************************************** OnPaint
        
        protected override void OnPaint ( PaintEventArgs e )
            {
            
            base.OnPaint ( e );

            if ( rectangles.Count > 0 )
                {
                e.Graphics.DrawRectangles ( new Pen ( Color.Black ),
                                            rectangles.ToArray ( ) );
                }
            if ( drawing )
                {
                e.Graphics.DrawRectangle ( new Pen ( Color.Red ), 
                                           current_rectangle ( ) );
                }
            }
            
        } // class DynamicRectangles

    } // namespace CodeProject


I have a couple of observations about your code.

1. From MSDN

The On... methods allow derived classes to handle the event without attaching a delegate.
This is the preferred technique for handling the event in a derived class.

I suggest that you use the On... form of event handler declaration. All you need to enter is protected override in your code and Intellisence will provide you with a list from which you can choose what you want.

2. I am ignoring the canevas [sic] variable.
3. I am ignoring the event handler rectangleShape1_Click.

Hope that helps.

Gus
 
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