基本信息
源码名称:经典串口编程案例源码(5路灯光控制以及投影仪开关)
源码大小:5.51M
文件格式:.rar
开发语言:C#
更新时间:2018-08-08
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Windows.Threading;
using System.Runtime.InteropServices;
using System.Windows.Media.Composition;
using System.Windows.Media.Animation;
using System.Threading;
using System.Net.Sockets;
using System.Reflection;
using System.Net;
using MyCom;
using System.IO.Ports;

namespace LJKJMedia
{
    /// <summary>
    /// MediaCtl.xaml 的交互逻辑
    /// </summary>
    public partial class MediaCtl : Window
    {
        #region 系统变量
        /// <summary>
        /// 读写配置文件帮助类
        /// </summary>
        private ReaderWriterIni rw;
        
        private string m_IsHideTask = "";//是否隐藏任务栏
        private string m_IsHideMouse = "";//是否隐藏鼠标

        private string m_AppPath = "";

        private string m_light1_on = string.Empty;
        private string m_light2_on = string.Empty;
        private string m_light3_on = string.Empty;
        private string m_light4_on = string.Empty;
        private string m_light5_on = string.Empty;

        private string m_light1_off = string.Empty;
        private string m_light2_off = string.Empty;
        private string m_light3_off = string.Empty;
        private string m_light4_off = string.Empty;
        private string m_light5_off = string.Empty;

        private string m_projector_on = string.Empty;
        private string m_projector_off = string.Empty;

        private bool light1OnOff = false;
        private bool light2OnOff = false;
        private bool light3OnOff = false;
        private bool light4OnOff = false;
        private bool light5OnOff = false;
        private bool lightAllOnOff = false;

        private string m_light1_name = string.Empty;
        private string m_light2_name = string.Empty;
        private string m_light3_name = string.Empty;
        private string m_light4_name = string.Empty;
        private string m_light5_name = string.Empty;

        private string[] projectorCom;

        private ComHelper com_Light = new ComHelper();
        private ComHelper com_Projector = new ComHelper();
        private bool bLight;
        private bool bProjector;

        UdpClient uc = null; //声明UDPClient
        private int m_UdpPort = 19000;
        private string m_UdpSvrIP = "";


        private Socket m_SvrSocket = null;
        private Socket m_ClentSocket = null;
        private Thread m_ThreadSocket = null;
        private string m_LocalIpAddress = "";
        private int m_LocalPort = 19001;

        //初始化串口端口
        private void InitComm()
        {
            //com.myEventRec  = new ComHelper.com1_DataReceived(com1RedDev_eventRec);
            bLight = com_Light.OpenPort_light();
            if (!bLight) { MessageBox.Show(com_Light.GetOpenedComLogMsg()); }

            bProjector = com_Projector.OpenPort_projector();
            if (!bProjector) { MessageBox.Show(com_Projector.GetOpenedComLogMsg()); }
        }


        #endregion

        #region 构造函数
        public MediaCtl()
        {
            InitializeComponent();
        }
        #endregion

        #region 产品化

        private const int SW_HIDE = 0;  //隐藏任务栏
        private const int SW_RESTORE = 9;//显示任务栏

        private void HideMouse()
        {
            cls_HideMouse.ShowCursor(false);
        }

        private void ShowMouse()
        {
            cls_HideMouse.ShowCursor(true);
        }

        private void HideTask()
        {
            cls_HideTask.ShowWindow(cls_HideTask.FindWindow("Shell_TrayWnd", null), SW_HIDE); //隐藏任务栏
            cls_HideTask.ShowWindow(cls_HideTask.FindWindow("Button", null), SW_HIDE);  //隐藏开始按钮
        }

        private void ShowTask()
        {
            cls_HideTask.ShowWindow(cls_HideTask.FindWindow("Shell_TrayWnd", null), SW_RESTORE); //显示任务栏
            cls_HideTask.ShowWindow(cls_HideTask.FindWindow("Button", null), SW_RESTORE);  //显示开始按钮
        }


        #endregion

        #region 初始化加载
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                m_AppPath = AppDomain.CurrentDomain.BaseDirectory;

                rw = new ReaderWriterIni(GlobalValue.iniPath);

                m_UdpPort = int.Parse(rw.ReaderIni("LJKJSetting", "UdpPort"));//UDP服务端口号
                m_UdpSvrIP = rw.ReaderIni("LJKJSetting", "UdpSvrIP");//UDP服务ip地址


                m_LocalPort = int.Parse(rw.ReaderIni("LJKJSetting", "LocalPort"));//tcp服务端口号

                m_LocalIpAddress = rw.ReaderIni("LJKJSetting", "LocalIpAddress");//tcp服务ip地址


                m_IsHideTask = rw.ReaderIni("LJKJSetting", "IsHideTask");
                m_IsHideMouse = rw.ReaderIni("LJKJSetting", "IsHideMouse");

                m_light1_on = rw.ReaderIni("lightComSetting", "light1_on");
                m_light2_on = rw.ReaderIni("lightComSetting", "light2_on");
                m_light3_on = rw.ReaderIni("lightComSetting", "light3_on");
                m_light4_on = rw.ReaderIni("lightComSetting", "light4_on");
                m_light5_on = rw.ReaderIni("lightComSetting", "light5_on");

                m_light1_off = rw.ReaderIni("lightComSetting", "light1_off");
                m_light2_off = rw.ReaderIni("lightComSetting", "light2_off");
                m_light3_off = rw.ReaderIni("lightComSetting", "light3_off");
                m_light4_off = rw.ReaderIni("lightComSetting", "light4_off");
                m_light5_off = rw.ReaderIni("lightComSetting", "light5_off");

                light1.Content = rw.ReaderIni("LJKJSetting", "light1_name");
                light2.Content = rw.ReaderIni("LJKJSetting", "light2_name");
                light3.Content = rw.ReaderIni("LJKJSetting", "light3_name");
                light4.Content = rw.ReaderIni("LJKJSetting", "light4_name");
                light5.Content = rw.ReaderIni("LJKJSetting", "light5_name");
                lightAll.Content = rw.ReaderIni("LJKJSetting", "lightAll_name");

                m_projector_on = rw.ReaderIni("projectorComSetting", "projector_on");
                m_projector_off = rw.ReaderIni("projectorComSetting", "projector_off");



                if(m_IsHideTask=="1")
                    HideTask();

                if (m_IsHideMouse == "1")
                    HideMouse();

                //InitUdp();
                StartListen();
                InitComm();//初始化串口端口
            }
            catch (Exception ex)
            {
                System.IO.File.AppendAllText("log.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")   "-MediaCtl--UserControl_Loaded-"   ex.Message   "\r\n");
            }
        }
        #endregion


         private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ShowMouse();
            ShowTask();
        }
         #region tcp控制

         

         private string GetLoacalIP()
         {
             string hostName = Dns.GetHostName();
             System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);
             for (int i = 0; i < addressList.Length; i  )
             {
                 if (addressList[i].IsIPv6LinkLocal == false)
                 {
                     return addressList[i].ToString();
                 }
             }

             return "";
         }


         private void StartListen()
         {

             try
             {
                 IPAddress address;

                 m_SvrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                 if (m_LocalIpAddress == null)
                     address = IPAddress.Parse(GetLoacalIP());
                 else
                     address = IPAddress.Parse(m_LocalIpAddress);

                 IPEndPoint endpoint = new IPEndPoint(address, m_LocalPort);
                 m_SvrSocket.Bind(endpoint);
                 m_SvrSocket.Listen(30);
                 m_ThreadSocket = new Thread(StartSocket);
                 m_ThreadSocket.IsBackground = true;
                 m_ThreadSocket.Start();
             }
             catch
             {
                 m_SvrSocket.Close();
             }
         }

         private void StartSocket()
         {
             while (true)
             {
                 try
                 {
                     m_ClentSocket = m_SvrSocket.Accept();
                     if (m_ClentSocket.Connected)
                     {
                         byte[] stream = new byte[80];
                         int iLen = m_ClentSocket.Receive(stream);
                         string message = System.Text.Encoding.UTF8.GetString(stream, 0, iLen);
                         RecMsg(message.Trim().ToLower());
                     }
                 }
                 catch
                 {
                     m_ClentSocket.Close();
                 }

             }
         }

         //处理接收的消息
         private void RecMsg(string strRec)
         {

             switch (strRec)
             {
                 case "single|1|light_on":
                     lightSendCmd(m_light1_on);
                     break;

                 case "single|2|light_on":
                     lightSendCmd(m_light2_on);
                     break;

                 case "single|3|light_on":
                     lightSendCmd(m_light3_on);
                     break;

                 case "single|4|light_on":
                     lightSendCmd(m_light4_on);
                     break;

                 case "single|5|light_on":
                     lightSendCmd(m_light5_on);
                     break;

                 case "single|1|light_off":
                     lightSendCmd(m_light1_off);
                     break;

                 case "single|2|light_off":
                     lightSendCmd(m_light2_off);
                     break;

                 case "single|3|light_off":
                     lightSendCmd(m_light3_off);
                     break;

                 case "single|4|light_off":
                     lightSendCmd(m_light4_off);
                     break;

                 case "single|5|light_off":
                     lightSendCmd(m_light5_off);
                     break;

                 case "single|alllight_on"://所有灯光开 关
                    lightSendCmd(m_light1_on);
                    Thread.Sleep(100);
                    lightSendCmd(m_light2_on);
                    Thread.Sleep(100);
                    lightSendCmd(m_light3_on);
                    Thread.Sleep(100);
                    lightSendCmd(m_light4_on);
                    Thread.Sleep(100);
                    lightSendCmd(m_light5_on);
                     break;
                 case "single|alllight_off":
                    lightSendCmd(m_light1_off);
                    Thread.Sleep(100);
                    lightSendCmd(m_light2_off);
                    Thread.Sleep(100);
                    lightSendCmd(m_light3_off);
                    Thread.Sleep(100);
                    lightSendCmd(m_light4_off);
                    Thread.Sleep(100);
                    lightSendCmd(m_light5_off);
                     break;

                 case "single|projector_on":
                     projectorCom = m_projector_on.Split(',');
                     for (int i = 0; i < projectorCom.Length; i  )
                     {
                         projectorSendCmd(projectorCom[i]);
                         Thread.Sleep(100);
                     }
                     break;

                 case "single|projector_off":
                     projectorCom = m_projector_off.Split(',');
                     for (int i = 0; i < projectorCom.Length; i  )
                     {
                         projectorSendCmd(projectorCom[i]);
                         Thread.Sleep(100);
                     }
                     break;

                 default:
                     break;
             }
         }
#endregion
         #region  udp控制

         private void InitUdp()
         {
             //注意此处端口号要与发送方相同
             uc = new UdpClient(m_UdpPort);

             //开一线程
             Thread th = new Thread(new ThreadStart(StartSocketSvr));

             //设置为后台
             th.IsBackground = true;
             th.Start();

         }

         /// <summary>
         /// 获取本机地址列表
         /// </summary>
         public string GetLocalAddresses()
         {
             // 获取主机名
             string strHostName = Dns.GetHostName();

             // 根据主机名进行查找
             IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);

             string retval = "";

             foreach (IPAddress ipaddress in iphostentry.AddressList)
             {
                 if (ipaddress.AddressFamily == AddressFamily.InterNetwork)
                 {
                     retval = ipaddress.ToString();
                     break;
                 }
             }
             return retval;
         }

         /// <summary>
         /// 开启UDP服务 
         /// </summary>
         private void StartSocketSvr()
         {
             if (m_UdpSvrIP == "" || m_UdpSvrIP == null || m_UdpSvrIP == "-1")
             {
                 m_UdpSvrIP = GetLocalAddresses();
             }


             //声明终结点
             IPEndPoint iep = new IPEndPoint(IPAddress.Parse(m_UdpSvrIP), m_UdpPort);
             while (true)
             {
                 //获得Form1发送过来的数据包
                 string text = System.Text.Encoding.UTF8.GetString(uc.Receive(ref iep));
                 Logs.Log.WriteLog("msg", "接受到的UDP消息--"   text);

                 //Cls_Log.WriteLog("收到消息"   text);
                 //this.Dispatcher.Invoke(new Action(() =>
                 //{
                 //    lstLog.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")   "  收到命令:"   text   "\r");
                 //}));

                 switch (text)
                 {


                     case "single|1|light_on":
                         lightSendCmd(m_light1_on);
                         break;

                     case "single|2|light_on":
                         lightSendCmd(m_light2_on);
                         break;

                     case "single|3|light_on":
                         lightSendCmd(m_light3_on);
                         break;

                     case "single|4|light_on":
                         lightSendCmd(m_light4_on);
                         break;

                     case "light5_on":
                         lightSendCmd(m_light5_on);
                         break;

                     case "single|1|light_off":
                         lightSendCmd(m_light1_off);
                         break;

                     case "single|2|light_off":
                         lightSendCmd(m_light2_off);
                         break;

                     case "single|3|light_off":
                         lightSendCmd(m_light3_off);
                         break;

                     case "single|4|light_off":
                         lightSendCmd(m_light4_off);
                         break;

                     case "single|5|light_off":
                         lightSendCmd(m_light5_off);
                         break;

                     case "single|projector_on":
                         projectorCom = m_projector_on.Split(',');
                         for (int i = 0; i < projectorCom.Length; i  )
                         {
                             projectorSendCmd(projectorCom[i]);
                             Thread.Sleep(100);
                         }
                         break;

                     case "single|projector_off":
                         projectorCom = m_projector_off.Split(',');
                         for (int i = 0; i < projectorCom.Length; i  )
                         {
                             projectorSendCmd(projectorCom[i]);
                             Thread.Sleep(100);
                         }
                         break;
                    
                     default:
                         break;
                 }

             }
         }
         #endregion

       
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                switch ((sender as Button).Tag.ToString())
                {
                    case "light1":
                        if (!light1OnOff)
                        {
                            lightSendCmd(m_light1_on);
                            light1OnOff = true;
                        }
                        else
                        {
                            lightSendCmd(m_light1_off);
                            light1OnOff = false;
                        }
                        
                        break;

                    case "light2":
                        if (!light2OnOff)
                        {
                            lightSendCmd(m_light2_on);
                            light2OnOff = true;
                        }
                        else
                        {
                            lightSendCmd(m_light2_off);
                            light2OnOff = false;
                        }
                        break;

                    case "light3":
                        if (!light3OnOff)
                        {
                            lightSendCmd(m_light3_on);
                            light3OnOff = true;
                        }
                        else
                        {
                            lightSendCmd(m_light3_off);
                            light3OnOff = false;
                        }
                        break;

                    case "light4":
                        if (!light4OnOff)
                        {
                            lightSendCmd(m_light4_on);
                            light4OnOff = true;
                        }
                        else
                        {
                            lightSendCmd(m_light4_off);
                            light4OnOff = false;
                        }
                        break;

                    case "light5":
                        if (!light5OnOff)
                        {
                            lightSendCmd(m_light5_on);
                            light5OnOff = true;
                        }
                        else
                        {
                            lightSendCmd(m_light5_off);
                            light5OnOff = false;
                        }
                        break;

                    case "lightAll":
                        if (!lightAllOnOff)
                        {
                            lightSendCmd(m_light1_on);
                            Thread.Sleep(100);
                            lightSendCmd(m_light2_on);
                            Thread.Sleep(100);
                            lightSendCmd(m_light3_on);
                            Thread.Sleep(100);
                            lightSendCmd(m_light4_on);
                            Thread.Sleep(100);
                            lightSendCmd(m_light5_on);
                            lightAllOnOff = true;
                        }
                        else
                        {
                            lightSendCmd(m_light1_off);
                            Thread.Sleep(100);
                            lightSendCmd(m_light2_off);
                            Thread.Sleep(100);
                            lightSendCmd(m_light3_off);
                            Thread.Sleep(100);
                            lightSendCmd(m_light4_off);
                            Thread.Sleep(100);
                            lightSendCmd(m_light5_off);
                            lightAllOnOff = false;
                        }
                        break;

                    case "projector_on":
                        projectorCom = m_projector_on.Split(',');
                        for (int i = 0; i < projectorCom.Length; i  )
                        {
                            projectorSendCmd(projectorCom[i]);
                            Thread.Sleep(100);
                        }
                        break;

                    case "projector_off":
                        projectorCom = m_projector_off.Split(',');
                        for (int i = 0; i < projectorCom.Length; i  )
                        {
                            projectorSendCmd(projectorCom[i]);
                            Thread.Sleep(100);
                        }
                        break;


                    case "return":
                        this.Close();
                        break;

                   
                    default:
                        
                        break;
                }
            }
            catch (Exception ex)
            {
                System.IO.File.AppendAllText("log.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")   "-MediaCtl--Image_MouseDown-"   ex.Message   "\r\n");
            }
        }

        /// <summary>
        /// light灯发送命令
        /// </summary>
        public void lightSendCmd(string cmd)
        {
            try
            {
                if (cmd == null)
                {
                    Logs.Log.WriteLog("com", "cmd == null");
                    return;
                }

                if (cmd == "")
                {
                    Logs.Log.WriteLog("com", "cmd == 空");
                    return;
                }

                com_Light.SendMessage(cmd, true);

            }
            catch (Exception e1)
            {
                Logs.Log.WriteLog("error", "异常执行 ZmdSendCmd()"   e1.Message);
            }
        }

        /// <summary>
        /// projector灯发送命令
        /// </summary>
        public void projectorSendCmd(string cmd)
        {
            try
            {
                if (cmd == null)
                {
                    Logs.Log.WriteLog("com", "cmd == null");
                    return;
                }

                if (cmd == "")
                {
                    Logs.Log.WriteLog("com", "cmd == 空");
                    return;
                }

                com_Projector.SendMessage(cmd, true);

            }
            catch (Exception e1)
            {
                Logs.Log.WriteLog("error", "异常执行 ZmdSendCmd()"   e1.Message);
            }
        }

    }
}