Skip to content

Instantly share code, notes, and snippets.

@tormaroe
Created July 4, 2011 16:00
Show Gist options
  • Select an option

  • Save tormaroe/1063534 to your computer and use it in GitHub Desktop.

Select an option

Save tormaroe/1063534 to your computer and use it in GitHub Desktop.
Oscilloscope user control (WinForms)
// JUST A TEST FORM WITH TWO SCOPE CONTROLS AND SOME RANDOM DATA
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
namespace Testapp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
scope1.ForeColor = Color.LightGreen;
scope2.ForeColor = Color.Orange;
}
public delegate void FooDelegate();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
scope1.Data = CreateRandomPoints(60, 280, 100).ToList();
scope2.Data = CreateRandomPoints(10, 280, 100).ToList();
RunRandomData(scope1);
RunRandomData(scope2);
}
private bool _closing;
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
_closing = true;
}
private void RunRandomData(Marosoft.Oscilloscope.Scope scope)
{
new Task(() =>
{
while (!_closing)
{
scope.Data = RandomAdjustData(scope.Data, 100);
scope.BeginInvoke(new FooDelegate(() => scope.Refresh()));
Thread.Sleep(200);
}
}).Start();
}
private static Random _random = new Random();
private static IEnumerable<Point> CreateRandomPoints(int size, int maxX, int maxY)
{
yield return new Point(0, _random.Next(maxY));
yield return new Point(maxX, _random.Next(maxY));
for (int i = 0; i < size - 2; i++)
yield return new Point(_random.Next(maxX), _random.Next(maxY));
}
private static IEnumerable<Point> RandomAdjustData(IEnumerable<Point> data, int maxY)
{
foreach (var item in data)
{
int newY = item.Y + _random.Next(-10, 10);
yield return new Point(item.X, newY > maxY ? maxY : newY < 0 ? 0 : newY);
}
}
}
}
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace Marosoft.Oscilloscope
{
public partial class Scope : UserControl
{
public Scope()
{
InitializeComponent();
}
public IEnumerable<Point> Data { get; set; }
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
RenderChart();
}
private void RenderChart()
{
if (Data == null)
return;
using (var g = base.CreateGraphics())
{
int xScale = ClientSize.Width / Data.Max(p => p.X);
int yScale = ClientSize.Height / Data.Max(p => p.Y);
var dataArray = Data
.OrderBy(p => p.X)
.Select(p => new Point(xScale * p.X, yScale * p.Y))
.ToArray();
var pen = new Pen(this.ForeColor);
for (int i = 0; i < dataArray.Length - 1; i++)
g.DrawLine(pen, dataArray[i], dataArray[i + 1]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment