I want to draw a line by mouse(interactively) , I used C# and WinForm, the line should appear at any time from the starting point(when the mouse press on the panel) to the current position of the mouse, exactly like drawing a line in Paint program.
but the code produces a lot of lines, i know why but i don't know how to overcome this problem
Here is my code:
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Graphics g;
Pen myPen = new Pen(Color.Red);
Point p = new Point();
bool flag = false;
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
flag = true;
p = e.Location;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (flag)
{
g = panel1.CreateGraphics();
myPen.Width = 3;
Point p2 = new Point();
p2 = e.Location;
g.DrawLine(myPen, p, p2);
}
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
flag = false;
}
}}
Any Help? i want to draw many lines and keep the code simple as possible!
You will need to better manage the drawing. Some pointers:
CreateGraphics
. Instead, use thePaint
event already provided by the control.Form
class unless you're drawing on the form.Here's an example class. It's inherited from
Panel
. Simply add this to a form, such as in the Form's constructor using something likethis.Controls.Add(new PanelWithMouseDraw());
.Note: this uses
Tuple
which I believe requires .NET 4.0 or above. You could replace this structure with something else, if need be...you just need to keep a list ofPoint
pairs.Simple fix, change the method
panel1_MouseMove
as follows:Keep in mind this will work with any mouse button down, left or right doesnt matter.
Edit1:
This should draw a straight line and all the previous ones.