To draw shapes on a Control's surface, you rely on its Paint event or override the OnPaint method of a custom/user Control. Avoid storing its Graphics object, as it becomes invalid upon the Control's invalidation. Utilize the Graphics object provided by the PaintEventArgs object for drawing.
The provided C# code attempts to draw rectangles based on mouse coordinates but faces issues due to an incorrect DrawRect() method invocation. To rectify this, pass the required arguments (e.Graphics, x, y) to the DrawRect() method.
In complex drawing scenarios, consider defining different methods to handle specialized drawing tasks, passing the e.Graphics object to these methods for drawing operations.
The following code snippet presents an example of drawing rectangles as the mouse moves:
using System; using System.Drawing; using System.Windows.Forms; public partial class Form1 : Form { public void Form1_MouseMove(object sender, MouseEventArgs e) { int x = e.X; int y = e.Y; DrawRect(e.Graphics, x, y); } private void Form1_Paint(object sender, PaintEventArgs e) { } public void DrawRect(Graphics gr, int rey, int rex) { Pen pen = new Pen(Color.Azure, 4); Rectangle rect = new Rectangle(0, 0, rex, rey); gr.DrawRectangle(pen, rect); } }
For additional drawing capabilities:
The above is the detailed content of How Can I Use the Paint Event to Draw Shapes Based on Mouse Position in C#?. For more information, please follow other related articles on the PHP Chinese website!