Visual Studio 如何在C#中通过按钮单击事件在窗体上绘图?

ix0qys7i  于 2023-03-19  发布在  C#
关注(0)|答案(2)|浏览(352)

我是C#新手,正在尝试弄清楚如何使用按钮单击事件绘制窗体。我知道绘制事件处理程序所需的参数是PaintEventArgs,而按钮单击事件处理程序传递EventArgs
如何通过单击按钮来绘制窗体?这一切都是在Visual Studio 2022中完成的

5us2dqdw

5us2dqdw1#

下面是一个在窗体单击时画图的最小示例:

  1. void Main()
  2. {
  3. var form1 = new Form1();
  4. form1.Show();
  5. }
  6. public class Form1 : Form
  7. {
  8. public Form1()
  9. {
  10. var colour = System.Drawing.Color.Black;
  11. this.Click += (s, e) =>
  12. {
  13. colour = System.Drawing.Color.Red;
  14. this.Invalidate();
  15. };
  16. this.Paint += (s, e) =>
  17. {
  18. using var pen = new System.Drawing.Pen(colour);
  19. e.Graphics.DrawLine(pen, 0, 0, 10, 20);
  20. };
  21. }
  22. }

如果线从黑色变为红色点击然后它的工作。

展开查看全部
lg40wkob

lg40wkob2#

你不能。
按钮单击事件无法启动绘制事件。通常,您可以使用.Invalidate()方法告诉系统下次需要重新绘制窗体。按钮单击必须更改“绘制内容”的效果,但不能更改“绘制时间”的效果。
下面是一个如何在表单上绘图的示例。每次按下按钮,就会有一个随机点添加到点列表中。

然后,系统决定何时绘制窗体,在列表中添加新点后,您可以在可能的情况下强制重新绘制。

  1. public partial class Form1 : Form
  2. {
  3. readonly static Random rng = new Random();
  4. readonly List<Point> pointList;
  5. public Form1()
  6. {
  7. InitializeComponent();
  8. pointList = new List<Point>();
  9. this.Paint += Form1_Paint;
  10. }
  11. private void Form1_Paint(object sender, PaintEventArgs e)
  12. {
  13. e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
  14. // Connect points with lines
  15. if (pointList.Count >= 2)
  16. {
  17. e.Graphics.DrawLines(Pens.Red, pointList.ToArray());
  18. }
  19. // Add a small square at each point
  20. foreach (var point in pointList)
  21. {
  22. e.Graphics.DrawRectangle(Pens.Black,
  23. point.X - 2, point.Y - 2, 4, 4);
  24. }
  25. }
  26. private void drawButton_Click(object sender, EventArgs e)
  27. {
  28. // Adds a random point on the list
  29. pointList.Add(new Point(
  30. rng.Next(this.ClientSize.Width),
  31. rng.Next(this.ClientSize.Height)));
  32. this.Invalidate();
  33. }
  34. }

还有.Refresh(),它会立即强制重绘,但通常不需要。
准确地说,你可以,但你不应该。下面的代码将触发和绘制事件,而不是调用.Invalidate()

  1. Graphics g = this.CreateGraphics();
  2. OnPaint(new PaintEventArgs(g, ClientRectangle));

最终效果是相同的,只是现在您正在扰乱Windows任务调度和UI事件的处理。

展开查看全部

相关问题