C# 图表绘制事件

C# 图表绘制事件,c#,winforms,events,charts,C#,Winforms,Events,Charts,以下是我正在运行的代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; using System.Drawing; namesp

以下是我正在运行的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Drawing;

namespace ChartTeste
{
    public partial class Form1 : Form
    {
        Graphics g;

        public Form1()
        {
            InitializeComponent();
            chart1.ChartAreas["Triangulos"].AxisY.Minimum = 0;
            chart1.ChartAreas["Triangulos"].AxisY.Maximum = 40;
            chart1.ChartAreas["Triangulos"].AxisX.Minimum = 0;
            chart1.ChartAreas["Triangulos"].AxisX.Maximum = 5;
            g = chart1.CreateGraphics();
        }

        private void chart1_Paint(object sender, PaintEventArgs e)
        {
            Paint();
        }

        private void Paint()
        {
            Pen p = new Pen(Brushes.Red);
                chart1.Series["PreçoT"].Points.AddXY(1, 0);

                double posiX = chart1.ChartAreas["Triangulos"].AxisX.ValueToPixelPosition(1);
                double posiY = chart1.ChartAreas["Triangulos"].AxisY.ValueToPixelPosition(13);
                double posiY2 = chart1.ChartAreas["Triangulos"].AxisY.ValueToPixelPosition(16);
                double max = chart1.ChartAreas["Triangulos"].AxisY.ValueToPixelPosition(19);
                double min = chart1.ChartAreas["Triangulos"].AxisY.ValueToPixelPosition(10);


                Point[] points = { new Point(Convert.ToInt32(posiX - 20), Convert.ToInt32(posiY)), new Point(Convert.ToInt32(posiX + 20), Convert.ToInt32(posiY)), new Point(Convert.ToInt32(posiX + 20), Convert.ToInt32(posiY2)) };

                g.DrawLine(p,Convert.ToInt32(posiX),Convert.ToInt32(min),Convert.ToInt32(posiX),Convert.ToInt32(max));
                g.FillPolygon(Brushes.Red, points);
        }
    }
}
当我运行它时,生成的三角形不是固定的,它会闪烁并出现故障。在绘制事件生成三角形后,是否有任何方法可以停止绘制事件


感谢您的帮助。

要停止闪烁,请添加
this.DoubleBuffered=true添加到窗体的构造函数中。
若要每隔X分钟重新绘制窗体,请添加
Invalidate(true)
在timer tick事件中(我假设您有timer)。

如果您只需要编码执行一次,为什么要将其放在图表的paint事件中?为什么不将其添加到构造函数中?绘制事件是危险的。它运行了很多次,这就是为什么你有这个闪烁。试着把它放在
Invalidated
@wazaaaap上,因为我不会在整个程序中只做一次。此代码用于演示目的。我将创建一个方法,每x分钟添加一个点。另外,如果我把它放在构造函数中,我会得到一个nullPointerNever,永远不要使用CreateGraphics()来绘制。它会出现“小故障”,因为您将像素直接飞溅到屏幕上。由于图表控件使用双缓冲,它们很快就会再次被过度渲染。始终使用
e.Graphics
,将其传递给您的Paint()方法。谢谢@HansPassant,但如何给三角形内部着色?虽然此代码可能会回答此问题,但提供有关此代码为什么和/或如何回答此问题的其他上下文将提高其长期价值。
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);