My goal is very simple. Imagine opening MSPaint, clicking the line tool, holding mouse down, and dragging it around. It anchors the starting coordinates where you clicked mouse down and constantly draws and redraws a line to your current position.
Except me trying to do this in C# isn't working as well as I would hope.
[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("User32.dll")]
static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
protected override void OnPaint(PaintEventArgs e)
{
endingPoint = GetMouseCoords();
DrawLine(startingPoint, endingPoint);
}
private void DrawLine(Point startingCoords, Point endingCoords)
{
IntPtr desktop = GetDC(IntPtr.Zero);
Pen pen = new Pen(Brushes.Red, 3);
using (Graphics g = Graphics.FromHdc(desktop))
{
g.DrawLine(pen, startingCoords.X, startingCoords.Y, endingCoords.X, endingCoords.Y);
g.Dispose();
}
ReleaseDC(IntPtr.Zero, desktop);
}
Using it this way, I only get the line drawn once. However, if I move the DrawLine() to a more static event like MouseUp, it will draw it, then disappear after about a quarter of a second.
What would be the best way to accomplish my goal here?
I would think that whatever event is being used to make the line disappear is what I would want to attach the drawing of the line to in the first place.
You need to have two drawing calls:
One for the non-persistent line that follows the cursor in the
MouseMove
usingsomeControls.CreateGraphics
the other for the persisting line, triggered in the
MouseUp
, whereInvalidate
on your canvas control andPaint
event of your canvas using itse.Graphics
object.Here is a minimal example code:
Note that this uses a
PictureBox
as the canvas control. It is the control meant for this kind of interaction. Your code seems to draw onto the desktop, which doesn't belong to you. Drawing onto it in a persistent manner is not anything like what you would do with the/any Paint application.Also note that my example stores a list of points and draws them as one non-closed Polyline. To draw them closed exchange
DrawLines
forDrawPolygon
! To draw several such polylines or polygons you need to..List<List, Point>>
Also note that this is one of the rare examples where using
control.CreateGraphics
is called for, as you actually do want a non-persistent drawing while the user moves the mouse.In most other cases the Winforms graphics basic rule #1 applies:
Never use
control.CreateGraphics
! Never try to cache aGraphics
object! Either draw into aBitmap bmp
using aGraphics g = Graphics.FromImage(bmp)
or in thePaint
event of a control, using thee.Graphics
parameter..