要使用WinForm繪制實時曲線圖,可以按照以下步驟進行操作:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RealTimeChart
{
public partial class Form1 : Form
{
private Random random = new Random();
private Timer timer = new Timer();
public Form1()
{
InitializeComponent();
// 設置圖表的樣式
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.ChartAreas[0].AxisX.Maximum = 100;
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = 100;
chart1.Series.Add("數據");
chart1.Series["數據"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series["數據"].Color = Color.Blue;
// 設置定時器
timer.Interval = 1000; // 每隔1秒鐘更新一次數據
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
// 生成隨機數據
double x = random.Next(0, 100);
double y = random.Next(0, 100);
// 添加數據到圖表中
chart1.Series["數據"].Points.AddXY(x, y);
// 只保留最新的100個數據點
if (chart1.Series["數據"].Points.Count > 100)
{
chart1.Series["數據"].Points.RemoveAt(0);
}
}
}
}
注意:在使用Chart控件前,需要在項目中引用System.Windows.Forms.DataVisualization庫。