Reputation: 1152
Beginner coder here getting into C#.. I'm making a program that involves drawing. Basically whenever I'm moving my mouse to draw, the actual line on the image appears delayed - and it's more.. straight, than it's supposed to be. It used to work fine, but at some point I guess something went wrong - can't remember what I did at the time so it's hard to retrace.. I tried to replicate just the drawing part of the program in a new solution, and it seems to work fine..
I'd post the .exe file so you can see what I mean but I'm not sure if we're allowed to post executables around here.
Edit: I've confirmed that the code works fine, look at the answer by sa_ddam213 for an example of the code. It seems as though it works fine in other peoples computers, so I'm completely confused.
Upvotes: 0
Views: 1104
Reputation: 117
May be It's a problem with your VGA . Check with another PC and let us know
Upvotes: 0
Reputation: 43596
Yo are creating a new Graphic and Pen object with every mouse move event, this will be a lot slower than creating these variables once in the Mouse_Down
event.
Something like this may be a bit faster.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
b = new Bitmap(this.Width, this.Height);
}
private Graphics _graphics;
private Pen _pen;
private int pX = 0;
private int pY = 0;
private bool paint = false;
private Bitmap b;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
pX = e.X;
pY = e.Y;
_graphics = Graphics.FromImage(b);
_pen= new Pen(Color.Black, 3);
paint = true;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (paint)
{
_graphics.DrawLine(_pen, pX, pY, e.X, e.Y);
pictureBox1.BackgroundImage = b;
pictureBox1.Refresh();
pX = e.X;
pY = e.Y;
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
paint = false;
_graphics.Dispose();
_pen.Dispose();
}
}
Upvotes: 1
Reputation: 109547
Instead of pictureBox1.Invalidate(), try using pictureBox1.Refresh()
You might also need to move it AFTER the pictureBox1.BackgroundImage = b
Also, in your MouseDown, you need to set this.Capture = true, and in your MouseUp you should set this.Capture = false. If you don't do that and you release the mouse button while your mouse cursor is over a different application, your's will never receive the MouseUp message.
Upvotes: 0