码迷,mamicode.com
首页 > 其他好文 > 详细

动态系统托盘图标

时间:2019-01-25 11:49:19      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:组件   accept   over   com   string   textbox   读取   监听   接受   

实现效果:

  技术分享图片

知识运用:

  TcpListener TcpClient  和  NetworkStream类 及  Timer组件

  1> TcpListener类    //用来从Tcp网络客户端侦听连接

  技术分享图片

  2> TcpClient类    //为Tcp网络服务提供客户端连接

  public TcpClient(string hostname,int port)  //远程主机的DNS名 端口号

  3> NetworkStream类  //提供在阻止模式下通过Stream套接字发送和接受数据的方法

    //其Read方法用于从NetworkStream类读取数据

  public override int Read(byte[] buffer,int offset,int size)

  技术分享图片

  4> notifyIcon控件的Icon属性

实现代码:

        //声明变量
        private Thread td;
        private string message = "";
        private TcpListener tcpListener;
        //监听方法
        private void startListen()
        {
            tcpListener = new TcpListener(999);
            tcpListener.Start();
            while (true)
            {
                TcpClient client = tcpListener.AcceptTcpClient();
                NetworkStream netStream = client.GetStream();
                byte[] bt=new byte[1024];
                netStream.Read(bt,0,bt.Length);
                message = Encoding.Default.GetString(bt);
            }
        }
        //发送消息
        private void button1_Click(object sender, EventArgs e)
        {
            TcpClient client = new TcpClient(textBox1.Text,999);
            string msg = "嗨,你好! 南极鱼";
            NetworkStream netStream = client.GetStream();
            StreamWriter sw = new StreamWriter(netStream);
            sw.WriteLine(msg);
            sw.Flush();
            sw.Close();
            client.Close();
        }
        //初始化
        private void Form1_Load(object sender, EventArgs e)
        {
            td = new Thread(new ThreadStart(startListen));
            td.Start();
            timer1.Start();
        }
        //清理工作
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (td.ThreadState == ThreadState.Running)
                td.Abort();
            if (tcpListener != null)
                tcpListener.Stop();
        }
        //定时检查有无消息
        bool flag;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (message.Length > 0)
            {
                if(flag)
                    { notifyIcon1.Icon = Properties.Resources._1; flag = false; }
                else
                    { notifyIcon1.Icon = Properties.Resources._2; flag = true; }
            }
        }
        //停止闪烁
        private void button2_Click(object sender, EventArgs e)
        {
            message = "";
            notifyIcon1.Icon = Properties.Resources._3;
        }

  

动态系统托盘图标

标签:组件   accept   over   com   string   textbox   读取   监听   接受   

原文地址:https://www.cnblogs.com/feiyucha/p/10317733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!