My question is related to Stack Overflow question Draw lines on a picturebox using mouse clicks in C#, but when the mouse button is up, the drawn line disappears. How do I fix this?
private void GainBox_MouseDn(object sender, MouseEventArgs e)
{
mouse_dn = true;
}
private void GainBox_MouseMv(object sender, MouseEventArgs e)
{
//Line drawn from lookup table
if (mouse_dn)
{
img = new Bitmap(256, 256);
//Get the coordinates (x, y) for line from lookup table.
for (x = x1; x < x2; x++)
img.SetPixel(x, y, Color.Red);
//Same for y coordinate
}
GainBox.Refresh();
}
private void GainBox_MouseUp(object sender, MouseEventArgs e)
{
mouse_dn = false;
}
Use Graphics Object to Drawline
e.g.
Here is a small complete program that does draw lines based on points (in this case, it follows the mouse). I think you can rework that into what you need.
One problem in your solution is that you are drawing on a temporary bitmap, but the image in that bitmap is never transferred to your
PictureBox
. In the solution presented here, there isn't any extra bitmap needed.gainbox.refresh()
should stay inside theif (mouse_dn)
clause.