Click here to Skip to main content
16,015,531 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to a line between two points using mouse move and second time
I click the mouse, a line will be draw and start drawing new line. I've tried use g.clear(backcolor) and refresh(), but when every time I move the mouse the lines appear and disappear. How I can solve this problem?

What I have tried:

namespace projebaslangıcLine2
{
public partial class Form1 : Form
{

private bool mouse_is_down = false;
private bool key_space = false;
private bool line_selected = false;
List<point> start_points;
List<point> finish_points;
private Point start;
private Point finish;
Graphics g;

public Form1()
{
InitializeComponent();
BackColor = Color.Black;
g = CreateGraphics();
start_points = new List<point>();
finish_points = new List<point>();

}

private void Form1_Load(object sender, EventArgs e)
{

}

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (line_selected == true && start.X == 0)
{
mouse_is_down = true;
start.X = e.X;
start.Y = e.Y;

}
else
{
finish.X = e.X;
finish.Y = e.Y;
start_points.Add(start);
finish_points.Add(finish);

Invalidate();
start.X = e.X;
start.Y = e.Y;
}

}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{

if (mouse_is_down == true && line_selected == true)
{
g.Clear(BackColor);
g.DrawLine(Pens.White, start, new Point(e.X,e.Y));
silenenleri_ciz();

}

}

private void Form1_Paint(object sender, PaintEventArgs e)
{
using (var p = new Pen(Color.White))
{
for (int x = 0; x < start_points.Count; x++)
{
g.DrawLine(p, start_points[x], finish_points[x]);

}
}
}

private void silenenleri_ciz()
{

for (int x = 0; x < start_points.Count; x++)
{

g.DrawLine(new Pen(Color.White), start_points[x], finish_points[x]);
}
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
key_space = true;
}
if (key_space == true && e.KeyCode == Keys.L)
{

mouse_is_down = false;
secilenKomut.Text = "Line";
line_selected = true;

}

}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
key_space = false;
}

private void secilenKomut_TextChanged(object sender, EventArgs e)
{

}

private void secilenKomut_Click(object sender, EventArgs e)
{
secilenKomut.TabStop = true;
}

}
}
Posted
Updated 2-Feb-19 5:19am
Comments
[no name] 3-Feb-19 22:02pm    
Why are you using "mouse move"? You only need 2 points (i.e. "clicks") to draw a line.
Member 14125168 5-Feb-19 7:09am    
Because I want to see angle of line by mouse move

1 solution

You should do all drawing inside in overload of the form's OnPaint method. See Control.OnPaint(PaintEventArgs) Method (System.Windows.Forms) | Microsoft Docs[^].
 
Share this answer
 
Comments
Maciej Los 3-Feb-19 16:33pm    
5ed!

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