您的位置:首页 > 编程语言 > C#

用c#实现类似QQ的简单通讯程序

2007-08-07 15:01 781 查看
本文介绍了用c#实现的一个类似QQ的局域网通讯程序,当点击最小化程序跑到系统托盘里,双击托盘可以可以显示主页面。

  程序运行界面如下:

  托盘里的菜单如下:

  c#作为微软.Net战略的重要棋子,对网络编程提供了很好的支持和优化。实现起来特别方便,还是看代码吧,已经注释的很清楚了。
代码如下:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Net.Sockets;
using System.Threading;
namespace p2pChat
{
  ///
  /// MainForm 的摘要说明。
  ///
  public class MainForm : System.Windows.Forms.Form
  {
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.TextBox txtIp;
    private System.Windows.Forms.TextBox txtRecord;
    private System.Windows.Forms.TextBox txtName;
    private System.Windows.Forms.Button btnSend;
    private System.Windows.Forms.TextBox txtContent;

    private TcpListener tcpLister = new TcpListener(5566);
    System.Threading.ThreadStart listenPort;
    System.Threading.Thread lister;
    private System.Windows.Forms.Label label3;
    System.Windows.Forms.NotifyIcon NotifyIcon1;
    //托盘里显示的图标,我用的是QQ里的宠物狗的图标
    private Icon img = new Icon(@"C:/OpenPet.ico");
    System.Windows.Forms.ContextMenu nMenu;
    ///
    /// 必需的设计器变量。
    ///
    private System.ComponentModel.Container components = null;
    public MainForm()
    {
        //
        // Windows 窗体设计器支持所必需的
        //
        InitializeComponent();

        //不显示最大化按钮
        this.MaximizeBox = false;
        //最小化时不显示在任务栏
        this.ShowInTaskbar = false;

listenPort += new ThreadStart(this.Listen);
        lister = new Thread(listenPort);
        this.Closing += new System.ComponentModel.CancelEventHandler(abortLister);
        Initializenotifyicon();
        //
        // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
        //
    }
    #region 初始化托盘组件
    private void Initializenotifyicon()
    {
        NotifyIcon1 = new NotifyIcon();
        NotifyIcon1.Icon = img;
        NotifyIcon1.Text = "局域网聊天程序";
        NotifyIcon1.Visible = true;
        NotifyIcon1.DoubleClick += new EventHandler(this.showMainForm);

        MenuItem [] menuArray = new MenuItem[3];
        menuArray[0] = new MenuItem();
        menuArray[0].Text = "显示主窗口";
        menuArray[0].Click += new EventHandler(this.showMainForm);
        menuArray[0].DefaultItem = true;

        menuArray[1] = new MenuItem("-");

        menuArray[2] = new MenuItem();
        menuArray[2].Text = "退出";
        menuArray[2].Click += new EventHandler(this.exitSystem);

        nMenu = new ContextMenu(menuArray);
        NotifyIcon1.ContextMenu = nMenu;
    }
    //显示主窗口
    private void showMainForm(object sender,System.EventArgs e)
    {
        this.WindowState = System.Windows.Forms.FormWindowState.Normal;
    }
    //退出程序
    private void exitSystem(object sender,System.EventArgs e)
    {
        NotifyIcon1.Visible = false;
        this.Close();
    }
    #endregion
    ///
    /// 清理所有正在使用的资源。
    ///
    protected override void Dispose( bool disposing )
    {
        if( disposing )
        {
         if (components != null)
         {
            components.Dispose();
         }
        }
       base.Dispose( disposing );
    }
    #region Windows 窗体设计器生成的代码
    ///
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    ///
    private void InitializeComponent()
{
        this.label1 = new System.Windows.Forms.Label();
        this.txtIp = new System.Windows.Forms.TextBox();
        this.txtRecord = new System.Windows.Forms.TextBox();
        this.label2 = new System.Windows.Forms.Label();
        this.txtName = new System.Windows.Forms.TextBox();
        this.btnSend = new System.Windows.Forms.Button();
        this.txtContent = new System.Windows.Forms.TextBox();
        this.label3 = new System.Windows.Forms.Label();
        this.SuspendLayout();
        //
        // label1
        //
        this.label1.Location = new System.Drawing.Point(16, 232);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(72, 23);
        this.label1.TabIndex = 0;
        this.label1.Text = "目标地址:";
        this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
        //
        // txtIp
        //
        this.txtIp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
        this.txtIp.Location = new System.Drawing.Point(80, 232);
        this.txtIp.Name = "txtIp";
        this.txtIp.Size = new System.Drawing.Size(200, 21);
        this.txtIp.TabIndex = 1;
        this.txtIp.Text = "";
        //
        // txtRecord
        //
        this.txtRecord.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
        this.txtRecord.Location = new System.Drawing.Point(16, 32);
        this.txtRecord.Multiline = true;
        this.txtRecord.Name = "txtRecord";
        this.txtRecord.ReadOnly = true;
        this.txtRecord.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
        this.txtRecord.Size = new System.Drawing.Size(264, 176);
        this.txtRecord.TabIndex = 4;
        this.txtRecord.Text = "";
        //
        // label2
        //
        this.label2.Location = new System.Drawing.Point(24, 256);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(48, 23);
        this.label2.TabIndex = 5;
        this.label2.Text = "呢 称:";
        this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
        //
        // txtName
        //
        this.txtName.Location = new System.Drawing.Point(80, 256);
        this.txtName.Name = "txtName";
        this.txtName.Size = new System.Drawing.Size(88, 21);
        this.txtName.TabIndex = 6;
        this.txtName.Text = "";
        //
        // btnSend
        //
        this.btnSend.Location = new System.Drawing.Point(200, 256);
        this.btnSend.Name = "btnSend";
        this.btnSend.Size = new System.Drawing.Size(64, 23);
        this.btnSend.TabIndex = 0;
        this.btnSend.Text = "发 送";
        this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
        //
        // txtContent
        //
        this.txtContent.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
         | System.Windows.Forms.AnchorStyles.Right)));
        this.txtContent.Location = new System.Drawing.Point(16, 288);
        this.txtContent.Multiline = true;
        this.txtContent.Name = "txtContent";
        this.txtContent.Size = new System.Drawing.Size(264, 152);
        this.txtContent.TabIndex = 8;
        this.txtContent.Text = "";
        //
        // label3
        //
        this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
         | System.Windows.Forms.AnchorStyles.Right)));
        this.label3.Location = new System.Drawing.Point(16, 8);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(100, 16);
        this.label3.TabIndex = 9;
        this.label3.Text = "聊天记录:";
        this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        //
        // MainForm
        //
        this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
        this.ClientSize = new System.Drawing.Size(292, 453);
        this.Controls.Add(this.label3);
        this.Controls.Add(this.txtContent);
        this.Controls.Add(this.btnSend);
        this.Controls.Add(this.txtName);
        this.Controls.Add(this.label2);
        this.Controls.Add(this.txtRecord);
        this.Controls.Add(this.txtIp);
        this.Controls.Add(this.label1);
        this.Name = "MainForm";
        this.Text = "局域网聊天程序";
        this.Load += new System.EventHandler(this.MainForm_Load);
        this.ResumeLayout(false);

}
    #endregion
    ///
    /// 应用程序的主入口点。
    ///
    [STAThread]
    static void Main()
    {
        Application.Run(new MainForm());
    }
    //开始监听
    private void Listen()
    {
        try
         {
           tcpLister.Start();
           while(true)
         {
           Socket s = tcpLister.AcceptSocket();
           Byte[] stream = new Byte[80];
           int i = s.Receive(stream);
           string message = System.Text.Encoding.UTF8.GetString(stream);
           this.txtRecord.AppendText(message);
         }
       }
       catch(System.Security.SecurityException)
       {
         MessageBox.Show("防火墙安全错误!","错误",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
       }
       catch(System.Exception)
       {
         //this.txtRecord.AppendText("已停止监听!");
       }
    }

    private void abortLister(object sender,System.ComponentModel.CancelEventArgs e)
    {
      this.tcpLister.Stop();
    }
    //发送
    private void btnSend_Click(object sender, System.EventArgs e)
{
if(this.txtContent.Text=="")
{
MessageBox.Show("不能发送空信息!","提示",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
        }
        else
        {
          this.Send();
      }
    }
    //发送消息
    private void Send()
    {
      try
      {
        string msg = this.txtName.Text+" ("+System.DateTime.Now.ToString()+")/r/n"+this.txtContent.Text+"/r/n";
        TcpClient client = new TcpClient(this.txtIp.Text,5566);
        NetworkStream sendStream = client.GetStream();
        StreamWriter writer = new StreamWriter(sendStream);
        writer.Write(msg);
        writer.Flush();
        sendStream.Close();
        client.Close();
        this.txtRecord.AppendText(msg);
        this.txtContent.Clear();
       }
       catch(System.Exception)
       {
         this.txtRecord.AppendText("目标计算机拒绝连接请求!/r/n");
       }
    }
    private void MainForm_Load(object sender, System.EventArgs e)
    {
        this.txtRecord.AppendText("正在监听.../r/n");
        lister.Name = "监听本地端口";
        lister.Start();
    }
  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: