首页 > 代码库 > C#温度报警

C#温度报警

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Drawing;

//展示端口
namespace TemperatureSytem
{
   static class ShowPortIsOrNo
    {
       /// <summary>
       /// 显示可用端口,和提示
       /// </summary>
       /// <param name="combox">显示端口</param>
       /// <param name="lab">提示</param>
       public static void FromLoadPort(ComboBox combox,Label lab)
       {
           ArrayList alPort = PortCheckAndSeting.PortSeting();
           if (alPort.Count < 1)
           {
               lab.Text = "未检测到可用串口!!!";
               lab.ForeColor = Color.Red;
               return;
           }
           else
           {
               foreach (string sPort in alPort)
               {
                   combox.Items.Add(sPort);
                   combox.Text = sPort;
               }
           }
       }
    }
}
ShowPortIsOrNo.cs
//串口检测
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO.Ports;
using System.Windows.Forms;

namespace TemperatureSytem
{
    static class PortCheckAndSeting
    {
        /// <summary>
        /// 加载的有串口
        /// </summary>
        /// <returns>返回一个串口动态数组</returns>
        public static ArrayList PortSeting()
        {
            ArrayList alPort = new ArrayList();
            foreach (string sPort in SerialPort.GetPortNames())
            {
                alPort.Add(sPort);
            }
            return alPort;
        }
        /// <summary>
        /// 新串口检测设置
        /// </summary>
        /// <param name="alOlePort"></param>
        /// <returns></returns>
        public static string NewPortSeting(ComboBox comBox)
        {
            //存在
            ArrayList alOldPort = new ArrayList();//保存旧串口号的
            foreach (string strOldPort in comBox.Items)//遍历旧的保存在动态数组里
            {
                alOldPort.Add(strOldPort);
            }
            foreach (string sPort in SerialPort.GetPortNames())
            {
                bool exists = ((IList)alOldPort).Contains(sPort);
                if (!exists)//在旧的串口里是否包含新检测的,不包含则返回这个新检测的
                    return sPort;
            }
            return "";
        }
    }
}
PortCheckAndSeting.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace TemperatureSytem
{
    class Sound
    {
        [DllImport("winmm.dll")]
        public static extern long PlaySound(String fileName, long a, long b);

        [DllImport("winmm.dll")]
        public static extern long mciSendString(string lpstrCommand, string lpstrReturnString, long length, long hwndcallback);

        /// <summary>
        /// 播放音乐文件(重复)
        /// </summary>
        /// <param name="p_FileName">音乐文件名称</param>
        public static void PlayMusic_Repeat(string p_FileName)
        {
            try
            {
                mciSendString(@"close temp_music", " ", 0, 0);
                mciSendString(@"open " + p_FileName + " alias temp_music", " ", 0, 0);
                mciSendString(@"play temp_music repeat", " ", 0, 0);
            }
            catch
            { }
        }

        /// <summary>
        /// 播放音乐文件
        /// </summary>
        /// <param name="p_FileName">音乐文件名称</param>
        public static void PlayMusic(string p_FileName)
        {
            try
            {
                mciSendString(@"close temp_music", " ", 0, 0);
                mciSendString(@"open " + p_FileName + " alias temp_music", " ", 0, 0);
                mciSendString(@"play temp_music", " ", 0, 0);
            }
            catch
            { }
        }

        /// <summary>
        /// 停止当前音乐播放
        /// </summary>
        /// <param name="p_FileName">音乐文件名称</param>
        public static void StopMusic(string p_FileName)
        {
            try
            {
                mciSendString(@"close " + p_FileName, " ", 0, 0);
            }
            catch { }
        }

      
    }
}
Sound.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Collections;
using System.Data.SqlClient;
using System.Diagnostics;

namespace SqlOperate
{
    class SqlHelpers
    {
        public bool bl = true;
        public static string sql;
        public static string userName;
        public static string userPwd;
        public static string sqlDatabase;
        public static string strConn;

        public string Sql
        {
            get { return sql; }
            set { sql = value; }
        }
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }
        public string UserPwd
        {
            get { return userPwd; }
            set { userPwd = value; }
        }
        public string SqlDataBase
        {
            get { return sqlDatabase; }
            set { sqlDatabase = value; }
        }


        public string StrrConn
        {
            get { return strConn; }
            set { strConn = value; }
        }
        OleDbConnection con;
        OleDbDataAdapter adp;
        //连接
        public string StrConnString()
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\data.mdb";
            return strConn;
        }
        public void Conn()
        {
            // string sqlconn = "server=" + sql + ";database="+sqlDatabase+";uid=" + userName + ";pwd=" + userPwd + ";";
            con = new OleDbConnection(StrConnString());
            try
            {
                con.Open();
                bl = true;
            }
            catch (Exception)
            {

                bl = false;
            }
        }
        #region 返回DataTable
        /// <summary>
        /// 返回DataTable
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable datatable(string sqlxx)
        {
            DataSet dataset = new DataSet();
            try
            {
                adp = new OleDbDataAdapter(sqlxx, StrConnString());
                adp.Fill(dataset, "table1");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return dataset.Tables["table1"];
        }
        #endregion

        #region 返回DATASET
        /// <summary>
        /// 返回DataTable
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataSet dataSet(string sqlxx)
        {
            DataSet dataset = new DataSet();
            try
            {
                adp = new OleDbDataAdapter(sqlxx, StrConnString());
                adp.Fill(dataset, "table1");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return dataset;
        }

        public DataSet dataSet(ArrayList sqlxx)
        {
            DataSet dataset = new DataSet();
            int i = 0;
            try
            {
                foreach (string item in sqlxx)
                {
                    adp = new OleDbDataAdapter(item, StrConnString());
                    adp.Fill(dataset,i.ToString());
                    i++;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return dataset;
        }
        #endregion

        #region 返回一个动态数组
        /// <summary>
        /// 返回一个动态数组
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="ziduan"></param>
        /// <param name="combox"></param>
        public ArrayList pinyin(string sql, string ziduan)
        {

            OleDbConnection con = new OleDbConnection(StrConnString());
            OleDbDataAdapter adp = new OleDbDataAdapter(sql, con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            ArrayList al = new ArrayList();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr2 = dt.Rows[i];
                string username = Convert.ToString(dr2[ziduan]);
                bool rep = false;
                foreach (string str in al)
                {
                    if (username == str)
                    {
                        rep = true;
                        break;
                    }
                }
                if (!rep)
                {
                    al.Add(username);
                }
            }
            return al;

        }
        #endregion

        #region 普通ExecuteNonQuery
        /// <summary>
        /// 普通ExecuteNonQuery
        /// </summary>
        /// <param name="sql"></param>
        public void ExecuteNonQuery(string sqlxx)
        {
            try
            {
                OleDbConnection con = new OleDbConnection(StrConnString());
                con.Open();
                OleDbCommand cmd = new OleDbCommand(sqlxx, con);
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch {throw new Exception(); }
           

        }
        #endregion

        #region 普通ExecuteNonQuery
        /// <summary>
        /// 数组ExecuteNonQuery
        /// </summary>
        /// <param name="sql"></param>
        public void ExecuteNonQuery(ArrayList sqlxx)
        {
            try
            {
                OleDbConnection con = new OleDbConnection(StrConnString());
                con.Open();
                foreach (string item in sqlxx)
                {
                    OleDbCommand cmd = new OleDbCommand(item, con);
                    cmd.ExecuteNonQuery();
                }

                con.Close();
            }
            catch { throw new Exception(); }


        }
        #endregion

        #region ComboBox下拉选择
        /// <summary>
        /// ComboBox下拉选择
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="ziduan"></param>
        /// <param name="combox"></param>
        public void Combox(string sql, string ziduan, ComboBox combox, int j)
        {
            combox.Items.Clear();
            OleDbConnection con = new OleDbConnection(StrConnString());
            OleDbDataAdapter adp = new OleDbDataAdapter(sql, con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            ArrayList al = new ArrayList();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr2 = dt.Rows[i];
                string username = Convert.ToString(dr2[ziduan]);
                bool rep = false;
                foreach (string str in al)
                {
                    if (username == str)
                    {
                        rep = true;
                        break;
                    }
                }
                if (!rep)
                {
                    al.Add(username);
                    combox.Items.Add(username);
                }
            }
            if (al.Count < 1)
            {
                combox.Text = "";
            }
            else
            {
                if (j == 0)
                {
                    combox.AutoCompleteCustomSource.AddRange((string[])al.ToArray(typeof(string))); //ArryList转为string[]
                    combox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
                    combox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
                }
                else
                {
                    combox.Text = al[0].ToString();
                    combox.AutoCompleteCustomSource.AddRange((string[])al.ToArray(typeof(string))); //ArryList转为string[]
                    combox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
                    combox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
                }

            }
        }
        #endregion

        #region 返回一个动态数组
        /// <summary>
        /// 返回一个动态数组含两个字段
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="ziduan"></param>
        /// <param name="combox"></param>
        public ArrayList TwoZiduan(string sql, string ziduan, string ziduan2)
        {

            OleDbConnection con = new OleDbConnection(StrConnString());
            OleDbDataAdapter adp = new OleDbDataAdapter(sql, con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            ArrayList al = new ArrayList();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr2 = dt.Rows[i];
                string username = Convert.ToString(dr2[ziduan]);
                string phonenumber = Convert.ToString(dr2[ziduan2]);
                string xx = username + "--" + phonenumber;
                bool rep = false;
                foreach (string str in al)
                {
                    if (xx == str)
                    {
                        rep = true;
                        break;
                    }
                }
                if (!rep)
                {
                    al.Add(xx);
                }
            }
            return al;

        }
        #endregion

        #region  提取一个字段int
        /// <summary>
        /// 提取一个字段int
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="ziduan"></param>
        /// <returns>int</returns>
        public int ReturnValue(string sql, string ziduan)
        {
            int IdValude = 0;
            OleDbConnection con = new OleDbConnection(StrConnString());
            OleDbDataAdapter adp = new OleDbDataAdapter(sql, con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                DataRow dr2 = dt.Rows[0];
                IdValude = Convert.ToInt32(dr2[ziduan]);
                return IdValude;
            }
            else
            {
                IdValude = -1;
                return IdValude;
            }
        }

        #endregion

        #region 提取一个字段string
        //提取一个字段string
        public string TextBox(string sql, string ziduan)
        {

            try
            {
                OleDbConnection con = new OleDbConnection(StrConnString());
                OleDbDataAdapter adp = new OleDbDataAdapter(sql, con);
                DataTable dt = new DataTable();
                adp.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    DataRow dr2 = dt.Rows[0];
                    return Convert.ToString(dr2[1]);
                }
                else
                {
                    return "";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return "";
            }
        }
        #endregion

        #region dataGridView美化
        /// <summary>
        /// dataGridView美化
        /// </summary>
        /// <param name="dataGridView"></param>
        public void dataGridView(DataGridView dataGridView)
        {
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            dataGridView.AllowUserToAddRows = false;
            dataGridView.AllowUserToDeleteRows = false;
            dataGridViewCellStyle1.BackColor = System.Drawing.Color.LightCyan;
            dataGridView.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
            dataGridView.BackgroundColor = System.Drawing.Color.White;
            dataGridView.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            dataGridView.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;//211, 223, 240
            dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(211)))), ((int)(((byte)(223)))), ((int)(((byte)(240)))));
            dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            dataGridViewCellStyle2.ForeColor = System.Drawing.Color.Navy;
            dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridView.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
            dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dataGridView.EnableHeadersVisualStyles = false;
            dataGridView.GridColor = System.Drawing.SystemColors.GradientInactiveCaption;
            dataGridView.ReadOnly = false ;
            dataGridView.RowHeadersVisible = false;
            dataGridView.RowTemplate.Height = 23;
            dataGridView.RowTemplate.ReadOnly = false ;
            dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        } 
        #endregion


        private void pilian(string tableName,string[] aa,string[] bb)
        {

            Stopwatch sw = new Stopwatch();
            OleDbConnection con = new OleDbConnection(StrConnString());
            OleDbCommand sqlComm = new OleDbCommand();
            sqlComm.CommandText = string.Format("insert into sz_tb (UserName,Pwd)values(@p0,@p1,@p2)");//参数化SQL
            sqlComm.Parameters.Add("@p0", SqlDbType.Int);
            sqlComm.Parameters.Add("@p1", SqlDbType.NVarChar);
            sqlComm.Parameters.Add("@p2", SqlDbType.VarChar);
            sqlComm.CommandType = CommandType.Text;
            sqlComm.Connection = con;
            con.Open();
            try
            {
                //循环插入100万条数据,每次插入10万条,插入10次。
                for (int multiply = 0; multiply < 10; multiply++)
                {
                    for (int count = multiply * 100000; count < (multiply + 1) * 100000; count++)
                    {

                        sqlComm.Parameters["@p0"].Value =http://www.mamicode.com/ count;
                        sqlComm.Parameters["@p1"].Value = http://www.mamicode.com/string.Format("User-{0}", count * multiply);
                        sqlComm.Parameters["@p2"].Value = http://www.mamicode.com/string.Format("Pwd-{0}", count * multiply);
                        sw.Start();
                        sqlComm.ExecuteNonQuery();
                        sw.Stop();
                    }
                    //每插入10万条数据后,显示此次插入所用时间
                   // Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }

            Console.ReadLine();
        }
    }
}
SqlHelpers.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using SqlOperate;
using System.Threading;
using System.Runtime.InteropServices;
using GSMMODEM;

namespace TemperatureSytem
{
    public partial class Form1 : Form
    {


        #region 窗体闪烁API
        [DllImport("user32.dll", EntryPoint = "FlashWindow")]
        public static extern bool FlashWindow(IntPtr handle, bool bInvert);
        [DllImport("user32.dll", EntryPoint = "AnimateWindow")]
        public static extern bool AnimateWindow(IntPtr handle, int dwTime, int dwFlags);

        public const Int32 AW_HOR_POSITIVE = 0x00000001;           //从左向右显示
        public const Int32 AW_HOR_NEGATIVE = 0x00000002;          //从右到左显示
        public const Int32 AW_VER_POSITIVE = 0x00000004;            //从上到下显示
        public const Int32 AW_VER_NEGATIVE = 0x00000008;           //从下到上显示
        public const Int32 AW_CENTER = 0x00000010; //若使用了AW_HIDE标志,则使窗口向内重叠,即收缩窗口;否则使窗口向外扩展,即展开窗口
        public const Int32 AW_HIDE = 0x00010000;                               //隐藏窗口,缺省则显示窗口
        public const Int32 AW_ACTIVATE = 0x00020000;                   //激活窗口。在使用了AW_HIDE标志后不能使用这个标志
        public const Int32 AW_SLIDE = 0x00040000;                           //使用滑动类型。缺省则为滚动动画类型。当使用AW_CENTER标志时,这个标志就被忽略
        public const Int32 AW_BLEND = 0x00080000;   
        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        SqlHelpers sqlHelpers = new SqlHelpers();//数据库类实例化
        delegate void set_Text(string s); //定义委托    
        set_Text Set_Text; //定义委托 
        double WoringTmp = 0;//临界温度
        bool bl = false;//奇偶次
        GsmModem gm = new GsmModem();//短信猫实例化

        private void Form1_Load(object sender, EventArgs e)
        {
            FromLoadSeting();
            Set_Text = new set_Text(set_lableText); //实例化
        }
        private void set_lableText(string s) //主线程调用的函数   
        {
            txt_nowTem.Text = s;
        }
        //窗体加载函数
        public void FromLoadSeting()
        {
           //ShowPortIsOrNo.FromLoadPort(cmb_Port, lab_ProtWoring);//温度感应器
           //ShowPortIsOrNo.FromLoadPort(cmb_sms_port, lab_sms_ProtWoring);//短信猫
        }

        #region 温度感应器配置
        //感应器串口检测
        private void timer_port_Tick(object sender, EventArgs e)
        {
            cmb_Port.Text = PortCheckAndSeting.NewPortSeting(cmb_Port);
            if (cmb_Port.Text == "")
            {
                lab_ProtWoring.Text = "未检测到可用串口!!!";
                lab_ProtWoring.ForeColor = Color.Red;
            }
            else
            {
                lab_ProtWoring.Text = "";
                lab_ProtWoring.ForeColor = Color.Red;
            }
        }


        //打开温度感应器串口
        private void btn_link_Click(object sender, EventArgs e)
        {
         
            OpenCgq();
           // timer1.Start();
        }

        /// <summary>
        /// 打开温度传感器
        /// </summary>
        private void OpenCgq()
        {
            if (cmb_Port.Text.Trim() == "")
            {
                MessageBox.Show("端口号不能为空");
                return;
            }
            btn_Close.Enabled = true;//关闭按钮可操作
            btn_link.Enabled = false;//打开按钮不可操作
            timer_port.Stop();//自动检测串口打开
            string CommNum = this.cmb_Port.Text;
            int IntBdr = Convert.ToInt32(this.cmb_rate.Text);//将串口号和波特率存起来
            if (!selPort.IsOpen)                      //如果串口是关闭的
            {
                selPort.PortName = CommNum;
                selPort.BaudRate = IntBdr;           //设定串口号和波特率
                try     //try:尝试下面的代码,如果错误就跳出来执行catch里面代码
                {
                    selPort.Open();          //打开串口
                    cmb_Port.Enabled = false;
                    cmb_rate.Enabled = false;        //将串口号与波特率选择控件关闭
                }
                catch
                {
                    MessageBox.Show("串口打开失败!\n\n可能是串口已被占用。");
                }
            }
            else//如果串口是打开的
            {
                selPort.Close();         //关闭串口;
                cmb_Port.Enabled = true;
                cmb_rate.Enabled = true;         //将串口号与波特率选择控件打开
                // hScrollBar1.Enabled = false;
            }
        }

        //关闭温度感应器串口;
        private void btn_Close_Click(object sender, EventArgs e)
        {
            btn_link.Enabled = true;//打开按钮可操作
            btn_Close.Enabled = false;//关闭按钮不可操作
            timer_port.Start();//自动检测串口打开
        } 
        #endregion

        #region 短信猫配置
        //短信猫 串口检测
        private void timer_sms_port_Tick(object sender, EventArgs e)
        {
            cmb_sms_port.Text = PortCheckAndSeting.NewPortSeting(cmb_Port);
            if (cmb_Port.Text == "")
            {
                lab_sms_ProtWoring.Text = "未检测到可用串口!!!";
                lab_sms_ProtWoring.ForeColor = Color.Red;
            }
            else
            {
                lab_sms_ProtWoring.Text = "";
                lab_sms_ProtWoring.ForeColor = Color.Red;
            }
        }

        private void btn_sms_link_Click(object sender, EventArgs e)
        {
            btn_sms_close.Enabled = true;//关闭按钮可操作
            btn_sms_link.Enabled = false;//打开按钮不可操作
            timer_sms_port.Stop();//自动检测串口打开
        }

        private void btn_sms_close_Click(object sender, EventArgs e)
        {
            btn_sms_link.Enabled = true;//打开按钮可操作
            btn_sms_close.Enabled = false;//关闭按钮不可操作
            timer_sms_port.Start();//自动检测串口打开
        } 
        #endregion

        string[] time = new string[12];
        float[] temper = new float[12];
        int hight = 3;
        private void button1_Click(object sender, EventArgs e)
        {
            BushImg();
        }

        private void BushImg()
        {
            //画图初始化
            Bitmap bmap = new Bitmap(500, 1000);
            Graphics gph = Graphics.FromImage(bmap);
            gph.Clear(Color.White);

            PointF cpt = new PointF(40, 420);//中心点
            PointF[] xpt = new PointF[3] { new PointF(cpt.Y + 15, cpt.Y), new PointF(cpt.Y, cpt.Y - 8), new PointF(cpt.Y, cpt.Y + 8) };//x轴三角形
            PointF[] ypt = new PointF[3] { new PointF(cpt.X, cpt.X - 15), new PointF(cpt.X - 8, cpt.X), new PointF(cpt.X + 8, cpt.X) };//y轴三角形
            gph.DrawString("温度分析折线图", new Font("宋体", 14), Brushes.Black, new PointF(cpt.X + 60, cpt.X));//图表标题
            //画x轴
            gph.DrawLine(Pens.Black, cpt.X, cpt.Y, cpt.Y, cpt.Y);
            gph.DrawPolygon(Pens.Black, xpt);
            gph.FillPolygon(new SolidBrush(Color.Black), xpt);
            gph.DrawString("", new Font("宋体", 12), Brushes.Black, new PointF(cpt.Y + 10, cpt.Y + 10));
            //画y轴
            gph.DrawLine(Pens.Black, cpt.X, cpt.Y, cpt.X, cpt.X);
            gph.DrawPolygon(Pens.Black, ypt);
            gph.FillPolygon(new SolidBrush(Color.Black), ypt);
            gph.DrawString("温度(°C)", new Font("宋体", 12), Brushes.Black, new PointF(0, 7));
            for (int i = 1; i <= 10; i++)
            {
                //画y轴刻度
                if (i < 11)
                {
                    gph.DrawString((i * 10).ToString(), new Font("宋体", 11), Brushes.Black, new PointF(cpt.X - 30, cpt.Y - i * 30 - 6));
                    gph.DrawLine(Pens.Black, cpt.X - 3, cpt.Y - i * 30, cpt.X, cpt.Y - i * 30);
                }

                //画x轴项目
                gph.DrawString(time[i - 1], new Font("宋体", 11), Brushes.Black, new PointF(cpt.X + i * 30 - 5, cpt.Y + 5));
                // gph.DrawString(time[i - 1], new Font("宋体", 11), Brushes.Black, new PointF(cpt.X + i * 30 - 5, cpt.Y + 20));
                if (time[i - 1].Length > 2) gph.DrawString(time[i - 1].Substring(2, 1), new Font("宋体", 11), Brushes.Black, new PointF(cpt.X + i * 30 - 5, cpt.Y + 35));
                //画点
                gph.DrawEllipse(Pens.Black, cpt.X + i * 30 - 1.5f, cpt.Y - temper[i - 1] * hight - 1.5f, 3, 3);
                gph.FillEllipse(new SolidBrush(Color.Black), cpt.X + i * 30 - 1.5f, cpt.Y - temper[i - 1] * hight - 1.5f, 3, 3);
                //画数值
                gph.DrawString(temper[i - 1].ToString(), new Font("宋体",6), Brushes.Black, new PointF(cpt.X + i * 30, cpt.Y - temper[i - 1] * hight));
                //画折线
                if (i > 1) gph.DrawLine(Pens.Red, cpt.X + (i - 1) * 30, cpt.Y - temper[i - 2] * hight, cpt.X + i * 30, cpt.Y - temper[i - 1] * hight);
            }
            //保存输出图片
            //bmap.Save(Response.OutputStream, ImageFormat.Gif);
            pictureBox1.Image = bmap;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            GetTimes();
            GetTimp();
        }

        //得到时间
        private void GetTimes()
        {
           for (int i = 1; i < 13; i++)
            {
                time[i-1] = i.ToString();
            }
        }

        private void GetTimp()
        {
            DataTable dt = sqlHelpers.datatable("select top 10 temper from temp_tb order by id desc");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                temper[i] = float.Parse( dt.Rows[i][0].ToString());
            }
            for (int i = dt.Rows.Count; i < 12; i++)
            {
                temper[i] = 0;
            }
            
        }

        int[] SDateTemp = new int[2];
        int cs = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            run();
          
        }


      
        //获得温度的并保存
        private void run()
        {
            while (true)
            {
                int temp = this.selPort.ReadByte();
                if (temp>10||bl)
                {
                    bl = true;
                    SDateTemp[cs] = temp;
                    cs++;
                    if (cs > 1)
                    {
                        string Temp = SDateTemp[0].ToString() + "." + SDateTemp[1].ToString();
                        sqlHelpers.ExecuteNonQuery("insert into temp_tb(temper)values(" + Temp + ")");
                        SDateTemp[0] = 0;
                        SDateTemp[1] = 1;
                        cs = 0;

                        txt_nowTem.Invoke(Set_Text, new object[] { Temp }); //通过调用委托,来改变TextBox的值 
                    }  
                }
            }
        }
        Thread thread1;
        private void button3_Click(object sender, EventArgs e)
        {

            thread1 = new Thread(new ThreadStart(run)); 
            thread1.Start();
            timer_woring.Start();
        }

        //刷新折线图
        private void timer_sx_Tick(object sender, EventArgs e)
        {
            GetTimes();
            GetTimp();
            BushImg();
        }

        //设置临界值
        private void btn_setTem_Click(object sender, EventArgs e)
        {
            WoringTmp = Convert.ToDouble(txt_worT.Text.Trim());
        }

        private void timer_woring_Tick(object sender, EventArgs e)
        {
            if (txt_nowTem.Text.Trim()!="")
            {
                if (Convert.ToDouble(txt_worT.Text.Trim()) < Convert.ToDouble(txt_nowTem.Text.Trim()))
                {
                    Sound.PlayMusic(Application.StartupPath + "\\woring.mp3");
                    timer_woring.Stop();
                    timer_ss.Start();
                    label7.Text = "温度过高!!!!";
                    string pic1 = Application.StartupPath + "\\1.gif";
                    this.pictureBox2.Image = Image.FromFile(pic1);
                    if (gm.IsOpen && txt_phoneNumber.Text != "" && txt_messages.Text!="")
                    {
                        gm.SendMsg(txt_phoneNumber.Text, txt_messages.Text);
                    }
                } 
            }
        }

        //解除警报
        private void btn_reaWoring_Click(object sender, EventArgs e)
        {
            Sound.PlayMusic(Application.StartupPath + "\\woring.mp");
            timer_woring.Start();
            timer_ss.Stop();
            label7.Text = "";
            string pic1 = Application.StartupPath + "\\2.jpg";
            this.pictureBox2.Image = Image.FromFile(pic1);
        }
        //窗体闪烁
        private void timer_ss_Tick(object sender, EventArgs e)
        {
            FlashWindow(this.Handle, true); 
        }

      
      
    }
}
From Code