1. 程式人生 > >動態系統托盤圖標

動態系統托盤圖標

buffer 讀取 ces lose nco info eight _for end

實現效果:

  技術分享圖片

知識運用:

  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;
        }

  

動態系統托盤圖標