C# 写上位机学习笔记

打开文件

       private void buttonOpenfile_Click(object sender, EventArgs e)
        {
            try
            {
                //在浏览的时候只显示后缀为db的文件
                fd.Filter = "表格文件|*.csv";
                if (fd.ShowDialog() == DialogResult.OK)                //获取导入
                {
                    filePath = fd.FileName;
                    textBox1.Text = filePath;//将上面获取到的路径放在文本框中   
                    string Line = GetNewLine(KeyIndex);
                }
                else
                {
                    return;
                }
            }
            catch
            {
                MessageBox.Show("读取数据出现错误,请检查文件重新读取数据");
            }
        }

保存日志文件

        public static void WriteLogFile(string str, string name)
        {
            StreamWriter sr;
            if (File.Exists(DateTime.Now.ToLongDateString().ToString() + name + ".txt")) //如果文件存在,则创建File.AppendText对象
            {
                sr = File.AppendText(DateTime.Now.ToLongDateString().ToString() + name + ".txt");
            }
            else   //如果文件不存在,则创建File.CreateText对象
            {
                sr = File.CreateText(DateTime.Now.ToLongDateString().ToString() + name + ".txt");
            }
            sr.WriteLine(str);
            sr.Close();
        }

TextBox自动滚动显示

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            textBoxHistoryLog.SelectionStart = textBoxHistoryLog.Text.Length;
            textBoxHistoryLog.SelectionLength = 0;
            textBoxHistoryLog.ScrollToCaret();
        }

TextBox限制输入

 private void textBox_InputKey_KeyPress(object sender, KeyPressEventArgs e)
 {
              if ((e.KeyChar >= '0' && e.KeyChar <= '9')|| e.KeyChar == '\b')
                {
                    e.Handled = false;
                }
                else
                {
                    e.Handled = true;
                }
 }

检测本机所有串口并刷新到comboBox

        private void buttonRefreshUart_Click(object sender, EventArgs e)
        {
            serialPort1.Close();
            comboBoxCom.Text = "未检测到串口";
            comboBoxCom.Items.Clear();
            foreach (string vPortName in SerialPort.GetPortNames())
            {
                comboBoxCom.Items.Add(vPortName);
                comboBoxCom.Text = vPortName;
            }
        }

dataGridView禁止选中单元格

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            dataGridView1.ClearSelection();
        }

建立TCP服务端

class TcpServer
    {
        public static int ConNum = 0;
        private string _ip = string.Empty;
        private int _port = 0;
        private Socket _socket = null;
        //RxDateHandle RxDate = new RxDateHandle();

        public TcpServer(string ip, int port)
        {
            this._ip = ip;
            this._port = port;
        }

        public TcpServer(int port)
        {
            this._ip = "0.0.0.0";
            this._port = port;
        }
        //开始监听
        public void StartListen()
        {
            try
            {
                //1.0 实例化套接字(IP4寻找协议,流式协议,TCP协议)
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //2.0 创建IP对象
                IPAddress address = IPAddress.Parse(_ip);
                //3.0 创建网络端口,包括ip和端口
                IPEndPoint endPoint = new IPEndPoint(address, _port);
                //4.0 绑定套接字
                _socket.Bind(endPoint);
                //5.0 设置最大连接数
                _socket.Listen(int.MaxValue);
                //Console.WriteLine("监听{0}消息成功", _socket.LocalEndPoint.ToString());
                //6.0 开始监听
                Thread thread = new Thread(ListenClientConnect);
                thread.Start();
                MyQueue.AddLogText("开始监听\r\n\r\n") ;
            }
            catch
            {
            }
        }
        /// <summary>
        /// 监听客户端连接
        /// </summary>
        private void ListenClientConnect()
        {
            try
            {
                while (true)
                {
                    //Socket创建的新连接
                    Socket clientSocket = _socket.Accept();
                    Thread thread = new Thread(UpdateTask);//开始接收客户端的消息
                    thread.Start(clientSocket);
                }
            }
            catch (Exception)
            {
            }
        }
        private void UpdateTask(object socket)
        {
            Socket clientSocket = (Socket)socket;
            PackFarme Frame = new PackFarme();
            DevIfoHandle DevIfo = new DevIfoHandle();
            byte[] TxBuf = new byte[264];
            byte[] RxBuf = new byte[264];
            while (true)  //首先监听数据
            {
                try
                {

                    //获取从客户端发来的数据

                    DevIfo.length = clientSocket.Receive(RxBuf).ToString();
                    DevIfo.IP = clientSocket.RemoteEndPoint.ToString();
                 
                    break;
                }
                catch 
                {
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    return;
                }
            }
        }
    }

用队列来传递消息

 class MyQueue
    {

        public static DevIfoHandle[] DevQueue = new DevIfoHandle[10];
        public static string[] LogText = new string[10];

        public static void AddDevIfo(DevIfoHandle Dev)
        {
            for (int i = 0; i < 10; i++)
            {
                if (DevQueue[i].ID == 0)
                {
                    DevQueue[i] = Dev;
                    break;
                }
            }
        }
        public static DevIfoHandle GetDevIfo()
        {
            DevIfoHandle result = new DevIfoHandle();
            for (int i = 0; i < 10; i++)
            {
                if (DevQueue[i].ID != 0)
                {
                    result = DevQueue[i];
                    DevQueue[i].ID = 0;
                    break;
                }
            }
            return result;
        }



        public static void AddLogText(string str)
        {
            for(int i = 0;i<10;i++)
            {
                if(LogText[i] == null)
                {
                    LogText[i] = str;

                    break;
                }
            }
        }

        public static string GetLogText()
        {
            string str = null;

            str = LogText[0];
            for (int i = 0; i < 9; i++)
            {
                LogText[i] = LogText[i + 1];

            }
            LogText[9] = null;
            return str;
        }
    }
  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值