C#自定义工业控件开发

简介:

由于工作需要,调研过一段时间的工业控制方面的“组态软件”(SCADA)的开发,组态软件常用于自动化工业控制领域,其中包括实时数据采集、数据储存、设备控制和数据展现等功能。其中工控组件的界面展现的实现类似于Windows系统下的各种开发控件,通过各种控件的组装,和硬件协议的集成,就可以实现对相应设备的控制和实时状态的显示。

每个对应的硬件UI展示都可以用一个自定义控件来实现,如下图的一个温度计,就可以使用UserControl来实现。

对应的实现代码如下:

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HMIControls
{
    public partial class ThermometerControl : UserControl
    {
        /// <summary>
        /// 初始化控件
        /// 预设绘图方式:双缓冲、支持透明背景色、自定义绘制
        /// </summary>
        public ThermometerControl()
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.Selectable, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            SetStyle(ControlStyles.UserPaint, true);

            InitializeComponent();
        }

        // 温度
        private float temperature = 0;
        [Category("温度"), Description("当前温度")]
        public float Temperature
        {
            set { temperature = value; }
            get { return temperature; }
        }

        // 最高温度
        private float highTemperature = 50;
        [Category("温度"), Description("最高温度")]
        public float HighTemperature
        {
            set { highTemperature = value; }
            get { return highTemperature; }
        }

        // 最低温度
        private float lowTemperature = -20;
        [Category("温度"), Description("最低温度")]
        public float LowTemperature
        {
            set { lowTemperature = value; }
            get { return lowTemperature; }
        }

        // 当前温度数值的字体
        private Font tempFont = new Font("宋体", 12);
        [Category("温度"), Description("当前温度数值的字体")]
        public Font TempFont
        {
            set { tempFont = value; }
            get { return tempFont; }
        }

        // 当前温度数值的颜色
        private Color tempColor = Color.Black;
        [Category("温度"), Description("当前温度数值的颜色")]
        public Color TempColor
        {
            set { tempColor = value; }
            get { return tempColor; }
        }

        // 大刻度线数量
        private int bigScale = 5;
        [Category("刻度"), Description("大刻度线数量")]
        public int BigScale
        {
            set { bigScale = value; }
            get { return bigScale; }
        }

        // 小刻度线数量
        private int smallScale = 5;
        [Category("刻度"), Description("小刻度线数量")]
        public int SmallScale
        {
            set { smallScale = value; }
            get { return smallScale; }
        }

        // 刻度字体
        private Font drawFont = new Font("Aril", 9);
        [Category("刻度"), Description("刻度数字的字体")]
        public Font DrawFont
        {
            get { return drawFont; }
            set { drawFont = value; }
        }

        // 字体颜色
        private Color drawColor = Color.Black;
        [Category("刻度"), Description("刻度数字的颜色")]
        public Color DrawColor
        {
            set { drawColor = value; }
            get { return drawColor; }
        }

        // 刻度盘最外圈线条的颜色
        private Color dialOutLineColor = Color.Gray;
        [Category("背景"), Description("刻度盘最外圈线条的颜色")]
        public Color DialOutLineColor
        {
            set { dialOutLineColor = value; }
            get { return dialOutLineColor; }
        }

        // 刻度盘背景颜色
        private Color dialBackColor = Color.Gray;
        [Category("背景"), Description("刻度盘背景颜色")]
        public Color DialBackColor
        {
            set { dialBackColor = value; }
            get { return dialBackColor; }
        }

        // 大刻度线颜色
        private Color bigScaleColor = Color.Black;
        [Category("刻度"), Description("大刻度线颜色")]
        public Color BigScaleColor
        {
            set { bigScaleColor = value; }
            get { return bigScaleColor; }
        }

        // 小刻度线颜色
        private Color smallScaleColor = Color.Black;
        [Category("刻度"), Description("小刻度线颜色")]
        public Color SmallScaleColor
        {
            set { smallScaleColor = value; }
            get { return smallScaleColor; }
        }

        // 温度柱背景颜色
        private Color mercuryBackColor = Color.LightGray;
        [Category("刻度"), Description("温度柱背景颜色")]
        public Color MercuryBackColor
        {
            set { mercuryBackColor = value; }
            get { return mercuryBackColor; }
        }

        // 温度柱颜色
        private Color mercuryColor = Color.Red;
        [Category("刻度"), Description("温度柱颜色")]
        public Color MercuryColor
        {
            set { mercuryColor = value; }
            get { return mercuryColor; }
        }

        /// <summary>
        ///  变量
        /// </summary>
        private float X;
        private float Y;
        private float H;
        private Pen p, s_p;
        private Brush b;

        /// <summary>
        /// 绘制温度计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThermometerControl_Paint(object sender, PaintEventArgs e)
        {
            // 温度值是否在温度表最大值和最小值范围内
            if (temperature > highTemperature)
            {
                //MessageBox.Show("温度值超出温度表范围,系统自动设置为默认值!");
                temperature = highTemperature;
            }
            if (temperature < lowTemperature)
            {
                temperature = lowTemperature;
            }

            e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            e.Graphics.TranslateTransform(2, 2);

            X = this.Width - 4;
            Y = this.Height - 4;

            // 绘制边框(最外边的框)
            p = new Pen(dialOutLineColor, 2);
            e.Graphics.DrawLine(p, 0, X / 2, 0, (Y - X / 2));
            e.Graphics.DrawLine(p, X, X / 2, X, (Y - X / 2));
            e.Graphics.DrawArc(p, 0, 0, X, X, 180, 180);
            e.Graphics.DrawArc(p, 0, (Y - X), X, X, 0, 180);

            // 绘制背景色
            X = X - 8;
            Y = Y - 8;
            b = new SolidBrush(dialBackColor);
            e.Graphics.TranslateTransform(4, 4);
            e.Graphics.FillRectangle(b, 0, X / 2, X, (Y - X));
            e.Graphics.FillEllipse(b, 0, 0, X, X);
            e.Graphics.FillEllipse(b, 0, (Y - X), X, X);

            // 绘制指示柱
            b = new SolidBrush(mercuryBackColor);
            e.Graphics.FillEllipse(b, X * 2 / 5, (X / 2 - X / 10), X / 5, X / 5);
            b = new SolidBrush(mercuryColor);
            e.Graphics.FillEllipse(b, X / 4, (Y - X * 9 / 16), X / 2, X / 2);
            e.Graphics.FillRectangle(b, X * 2 / 5, (X / 2 + 1), X / 5, (Y - X));

            // 在温度计底部,绘制当前温度数值
            b = new SolidBrush(tempColor);
            StringFormat format = new StringFormat();
            format.LineAlignment = StringAlignment.Center;
            format.Alignment = StringAlignment.Center;
            e.Graphics.DrawString((temperature.ToString() + ""), tempFont, b, X / 2, (Y - X / 4), format);

            // 绘制大刻度线,线宽为2
            // 绘制小刻度线,线宽为1
            // 绘制刻度数字,字体,字号,字的颜色在属性中可改
            p = new Pen(bigScaleColor, 2);                        // 设置大刻度线的颜色,线粗
            s_p = new Pen(smallScaleColor, 1);                      // 设置小刻度线的颜色,线粗
            SolidBrush drawBrush = new SolidBrush(drawColor);   // 设置绘制数字的颜色
            format.Alignment = StringAlignment.Near;            // 设置数字水平对齐为中间,垂直对其为左边
            // 计算要绘制数字的数值
            int interval = (int)(highTemperature - lowTemperature) / bigScale;
            int tempNum = (int)highTemperature;
            for (int i = 0; i <= bigScale; i++)
            {
                float b_s_y = X / 2 + i * ((Y - X - X / 2) / bigScale);       // 绘制大刻度线的垂直位置
                e.Graphics.DrawLine(p, X / 5, b_s_y, (X * 2 / 5 - 2), b_s_y); // 绘制大刻度线
                e.Graphics.DrawString(tempNum.ToString(), drawFont, drawBrush, X * 3 / 5, b_s_y, format);   // 绘制刻度数字
                tempNum -= interval;    // 计算下一次要绘制的数值

                // 绘制小刻度线
                if (i < bigScale)
                {
                    for (int j = 1; j < smallScale; j++)
                    {
                        float s_s_y = b_s_y + ((X / 2 + (i + 1) * ((Y - X - X / 2) / bigScale) - b_s_y) / smallScale) * j;
                        e.Graphics.DrawLine(s_p, (X * 3 / 10), s_s_y, (X * 2 / 5 - 2), s_s_y);
                    }
                }
            }
            
            // 计算当前温度的位置            
            float L = Y - X * 3 / 2;
            H = L * (temperature - lowTemperature) / (highTemperature - lowTemperature);
            // 绘制当前温度的位置
            b = new SolidBrush(mercuryBackColor);
            e.Graphics.FillRectangle(b, X * 2 / 5, X / 2, X / 5, (L - H));
        }
    }
}
复制代码

类似的一些实现,如下图:

对应一些动态线条的绘制,可以采用ZedGraph这个开源的控件来实现,如下图:

模拟的一些随时间变化的温度曲线图,一些参考代码如下:

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZedGraph;

namespace HMIControls
{
    public partial class AirMachine : UserControl
    {
        private bool isValveOn;
        private Timer timer;
        private double temperature;
        private Random random = new Random();

        private Point arrowLocation1;
        private Point arrowLocation2;
        private Point arrowLocation3;

        // Starting time in milliseconds
        int tickStart = 0;

        public AirMachine()
        {
            InitializeComponent();
            InitUI();
        }

        private void InitUI()
        {
            isValveOn = false;
            this.labelTemperature.Text = "0";
            this.button1.Text = "";
            this.button1.BackColor = Color.Snow;
            timer = new Timer();
            timer.Interval = 1000;
            timer.Tick += new EventHandler(timer_Tick);
            this.Load += new EventHandler(AirMachine_Load);

            this.labelArrow1.Visible = false;
            this.labelArrow2.Visible = false;
            this.labelArrow3.Visible = false;

            arrowLocation1 = this.labelArrow1.Location;
            arrowLocation2 = this.labelArrow2.Location;
            arrowLocation3 = this.labelArrow3.Location;

            this.button1.Click += new EventHandler(button1_Click);
        }

        private void CreateGraph()
        {
            zedGraphControl1.IsEnableZoom = false;
            zedGraphControl1.IsShowContextMenu = false;

            // Get a reference to the GraphPane
            GraphPane myPane = zedGraphControl1.GraphPane;

            // Set the titles
            myPane.Title.Text = "实时数据";
            myPane.YAxis.Title.Text = "数据";
            myPane.XAxis.Title.Text = "时间";

            // Change the color of the title
            myPane.Title.FontSpec.FontColor = Color.Green;
            myPane.XAxis.Title.FontSpec.FontColor = Color.Green;
            myPane.YAxis.Title.FontSpec.FontColor = Color.Green;


            // Save 1200 points.  At 50 ms sample rate, this is one minute
            // The RollingPointPairList is an efficient storage class that always
            // keeps a rolling set of point data without needing to shift any data values
            RollingPointPairList list = new RollingPointPairList(1200);

            // Initially, a curve is added with no data points (list is empty)
            // Color is blue, and there will be no symbols
            LineItem myCurve = myPane.AddCurve("温度值", list, Color.Blue, SymbolType.None);

            // Fill the area under the curves
            myCurve.Line.Fill = new Fill(Color.White, Color.Blue, 45F);

            myCurve.Line.IsSmooth = true;
            myCurve.Line.SmoothTension = 0.5F;

            // Increase the symbol sizes, and fill them with solid white
            myCurve.Symbol.Size = 8.0F;
            myCurve.Symbol.Fill = new Fill(Color.Red);
            myCurve.Symbol.Type = SymbolType.Circle;

            // Just manually control the X axis range so it scrolls continuously
            // instead of discrete step-sized jumps
            myPane.XAxis.Scale.Min = 0;
            myPane.XAxis.Scale.Max = 100;
            myPane.XAxis.Scale.MinorStep = 1;
            myPane.XAxis.Scale.MajorStep = 5;

            // Add gridlines to the plot
            myPane.XAxis.MajorGrid.IsVisible = true;
            myPane.XAxis.MajorGrid.Color = Color.LightGray;
            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.MajorGrid.Color = Color.LightGray;

            // Scale the axes
            zedGraphControl1.AxisChange();

            // Save the beginning time for reference
            tickStart = Environment.TickCount;
        }

        void AirMachine_Load(object sender, EventArgs e)
        {
            CreateGraph();
        }

        private void UpdateZedGraph(double yValue)
        {
            // Make sure that the curvelist has at least one curve
            if (zedGraphControl1.GraphPane.CurveList.Count <= 0)
                return;

            // Get the first CurveItem in the graph
            LineItem curve = zedGraphControl1.GraphPane.CurveList[0] as LineItem;
            if (curve == null)
                return;

            // Get the PointPairList
            IPointListEdit list = curve.Points as IPointListEdit;
            // If this is null, it means the reference at curve.Points does not
            // support IPointListEdit, so we won't be able to modify it
            if (list == null)
                return;

            // Time is measured in seconds
            double time = (Environment.TickCount - tickStart) / 1000.0;

            // 3 seconds per cycle
            //list.Add(time, Math.Sin(2.0 * Math.PI * time / 3.0));
            list.Add(time, yValue);

            // Keep the X scale at a rolling 30 second interval, with one
            // major step between the max X value and the end of the axis
            Scale xScale = zedGraphControl1.GraphPane.XAxis.Scale;
            if (time > xScale.Max - xScale.MajorStep)
            {
                xScale.Max = time + xScale.MajorStep;
                xScale.Min = xScale.Max - 100.0;
            }

            // Make sure the Y axis is rescaled to accommodate actual data
            zedGraphControl1.AxisChange();
            // Force a redraw
            zedGraphControl1.Invalidate();
        }

        private void UpdataArrowPosition()
        {
            this.labelArrow1.Location = new Point(this.labelArrow1.Location.X + 30, this.labelArrow1.Location.Y);
            if (this.labelArrow1.Location.X >= this.panelPic.Location.X + this.panelPic.Width)
            {
                this.labelArrow1.Location = arrowLocation1;
            }

            this.labelArrow2.Location = new Point(this.labelArrow2.Location.X + 30, this.labelArrow2.Location.Y);
            if (this.labelArrow2.Location.X >= this.panelPic.Location.X + this.panelPic.Width)
            {
                this.labelArrow2.Location = arrowLocation2;
            }

            this.labelArrow3.Location = new Point(this.labelArrow3.Location.X + 30, this.labelArrow3.Location.Y);
            if (this.labelArrow3.Location.X >= this.panelPic.Location.X + this.panelPic.Width)
            {
                this.labelArrow3.Location = arrowLocation3;
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            temperature = random.NextDouble() * 100;
            this.labelTemperature.Text = Convert.ToInt32(temperature).ToString();

            UpdateZedGraph(temperature);

            UpdataArrowPosition();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            isValveOn = !isValveOn;
            if (isValveOn)
            {
                timer.Start();
                this.button1.Text = "";
                this.button1.BackColor = Color.LawnGreen;
                this.labelTemperature.BackColor = Color.LawnGreen;
                this.labelArrow1.Visible = isValveOn;
                this.labelArrow2.Visible = isValveOn;
                this.labelArrow3.Visible = isValveOn;
            }
            else
            {
                timer.Stop();
                this.button1.Text = "";
                this.button1.BackColor = Color.Snow;
                this.labelTemperature.Text = "0";
                this.labelTemperature.BackColor = Color.Snow;
                this.labelArrow1.Visible = isValveOn;
                this.labelArrow2.Visible = isValveOn;
                this.labelArrow3.Visible = isValveOn;
            }
        }
    }
}
复制代码

整个组态软件的开发,从底层硬件相关的设备协议到上层的展现都是比较有难度的,特别是现在硬件协议不统一,业界没有统一的标准,虽然有OPC和BACnet等一些标准协议,但是在实际项目中,有很多的设备是没有实现OPC的,都是自己的私有协议,要基于这类的硬件做二次开发,需要向商家买协议,这也是成本的问题。

 

代码下载:http://download.csdn.net/detail/luxiaoxun/8256371

 

组态界面开发的一些参考资源:

http://www.codeproject.com/Articles/36116/Industrial-Controls

http://www.codeproject.com/Articles/17559/A-fast-and-performing-gauge

http://dashboarding.codeplex.com/

 

    本文转自阿凡卢博客园博客,原文链接:http://www.cnblogs.com/luxiaoxun/p/4161782.html,如需转载请自行联系原作者



相关文章
|
1月前
|
SQL 开发框架 .NET
C#一分钟浅谈:数据绑定与数据源控件
在Web开发中,数据绑定和数据源控件是实现动态网页的关键技术。本文从基础概念入手,详细讲解数据绑定的原理及其在ASP.NET中的应用,并介绍常见数据绑定方式:手动绑定和自动绑定。接着,文章重点介绍了ASP.NET中的数据源控件,如`SqlDataSource`、`ObjectDataSource`、`XmlDataSource`和`LinqDataSource`,并通过具体示例演示如何使用`SqlDataSource`和`GridView`进行数据绑定。最后,还列举了一些常见问题及其解决办法,帮助读者更好地理解和应用这些技术。
61 4
|
5天前
|
前端开发 JavaScript 安全
C#一分钟浅谈:Blazor WebAssembly 开发
Blazor WebAssembly 是一个客户端框架,允许开发者使用C#和Razor语法构建Web应用。本文介绍了Blazor WebAssembly的基本概念、常见问题及解决方案,包括路由配置、数据绑定、异步操作、状态管理和性能优化等方面的内容,并分享了一些易错点及如何避免的方法。希望这些内容能帮助你在Blazor WebAssembly开发中少走弯路,提高开发效率。
69 51
|
2天前
|
开发框架 缓存 .NET
C# 一分钟浅谈:Blazor Server 端开发
Blazor Server 是基于 ASP.NET Core 的框架,允许使用 C# 和 Razor 语法构建交互式 Web 应用。本文介绍 Blazor Server 的基本概念、快速入门、常见问题及解决方案,帮助开发者快速上手。涵盖创建应用、基本组件、数据绑定、状态管理、跨组件通信、错误处理和性能优化等内容。
8 1
|
3天前
|
缓存 C# 开发者
C# 一分钟浅谈:Blazor Server 端开发
本文介绍了 Blazor Server,一种基于 .NET 的 Web 开发模型,允许使用 C# 和 Razor 语法构建交互式 Web 应用。文章从基础概念、创建应用、常见问题及解决方案、易错点及避免方法等方面详细讲解,帮助开发者快速上手并提高开发效率。
16 2
|
13天前
|
测试技术 Go C#
C#一分钟浅谈:ReSharper 插件增强开发效率
【10月更文挑战第25天】ReSharper 是 JetBrains 开发的一款 Visual Studio 插件,旨在提高 .NET 开发者的生产力。它通过代码分析、重构、导航等功能,帮助开发者避免常见错误,提升代码质量和开发效率。本文将通过具体代码案例,详细介绍 ReSharper 的常见功能及其应用。
29 1
|
18天前
|
C# Python
使用wxpython开发跨平台桌面应用,对wxpython控件实现类似C#扩展函数处理的探究
【10月更文挑战第30天】使用 `wxPython` 开发跨平台桌面应用时,可以通过创建辅助类来模拟 C# 扩展函数的功能。具体步骤包括:1. 创建辅助类 `WxWidgetHelpers`;2. 在该类中定义静态方法,如 `set_button_color`;3. 在应用中调用这些方法。这种方法提高了代码的可读性和可维护性,无需修改 `wxPython` 库即可为控件添加自定义功能。但需要注意显式调用方法和避免命名冲突。
|
26天前
|
JSON C# 开发者
C#语言新特性深度剖析:提升你的.NET开发效率
【10月更文挑战第15天】C#语言凭借其强大的功能和易用性深受开发者喜爱。随着.NET平台的演进,C#不断引入新特性,如C# 7.0的模式匹配和C# 8.0的异步流,显著提升了开发效率和代码可维护性。本文将深入探讨这些新特性,助力开发者在.NET开发中更高效地利用它们。
30 1
|
1月前
|
开发框架 NoSQL MongoDB
C#/.NET/.NET Core开发实战教程集合
C#/.NET/.NET Core开发实战教程集合
|
2月前
|
物联网 C# C语言
物联网开发中C、C++和C#哪个更好用
在物联网(IoT)开发中,C、C++和C#各有优缺点,适用场景不同。C语言性能高、资源占用低,适合内存和计算能力有限的嵌入式系统,但开发复杂度高,易出错。C++支持面向对象编程,性能优秀,适用于复杂应用,但学习曲线陡峭,编译时间长。C#易于学习,与.NET框架结合紧密,适合快速开发Windows应用,但性能略低,平台支持有限。选择语言需根据具体项目需求、复杂性和团队技术栈综合考虑。
|
1月前
|
XML 存储 安全
C#开发的程序如何良好的防止反编译被破解?ConfuserEx .NET混淆工具使用介绍
C#开发的程序如何良好的防止反编译被破解?ConfuserEx .NET混淆工具使用介绍
49 0