Chat_Main
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Threading; 10 using System.Net; 11 using System.Net.Sockets; 12 using System.Reflection; 13 using System.Runtime.InteropServices; 14 using System.Messaging; 15 16 namespace JToolDemo.Tool_Chat 17 { 18 public partial class Chat_Main : NotifyIconForm 19 { 20 public Chat_Main() 21 { 22 InitializeComponent(); 23 } 24 25 #region 常量 26 /// <summary>对列表操作 添加</summary> 27 private const string LIST_TYPE_ADD = "ADD"; 28 /// <summary>对列表操作 删除</summary> 29 private const string LIST_TYPE_DEL = "DEL"; 30 #endregion 31 32 #region 变量 33 #endregion 34 35 #region 代理 36 /// <summary>给列表赋值 显示在线人数</summary> 37 delegate void invokeSetUserList(DataInfo tempReceiveInfo, string listType); 38 void onSetUserList(DataInfo tempReceiveInfo, string listType) 39 { 40 if (LIST_TYPE_ADD.Equals(listType)) 41 { 42 userListTable.Items.Add(userInfoSplice(tempReceiveInfo)); 43 } 44 else if (LIST_TYPE_DEL.Equals(listType)) 45 { 46 userListTable.Items.Remove(userInfoSplice(tempReceiveInfo)); 47 } 48 49 onlineCount.Text = string.Format("在线:{0}人" 50 , (userListTable.Items.Count).ToString()); 51 52 //最小化图标提示 53 this.minIcon.Text = string.Format("在线:{0}人" 54 , (userListTable.Items.Count).ToString()); 55 } 56 57 /// <summary>检查窗体时候打开</summary> 58 delegate bool invokeFormIsExist(string formName); 59 bool formIsExist(string formName) 60 { 61 Form tempForm = Application.OpenForms[formName]; 62 if (tempForm != null) 63 { 64 FormWindowState fws = new FormWindowState(); 65 //还原窗体 66 if (tempForm.WindowState == FormWindowState.Minimized) 67 { 68 object obj = fws; 69 Type p = tempForm.GetType(); 70 PropertyInfo myPropInfo = p.GetProperty("MinPreState"); 71 72 FormWindowState preState = (FormWindowState)myPropInfo.GetValue(tempForm, null); 73 tempForm.WindowState = preState; 74 } 75 //激活窗体 76 tempForm.Activate(); 77 return true; 78 } 79 80 //foreach (Form tempForm in Application.OpenForms) 81 //{ 82 // //Aha...found it 83 // if (tempForm.Text == formName) 84 // { 85 // FormWindowState fws = new FormWindowState(); 86 // //还原窗体 87 // if (tempForm.WindowState == FormWindowState.Minimized) 88 // { 89 // object obj = fws; 90 // Type p = tempForm.GetType(); 91 // PropertyInfo myPropInfo = p.GetProperty("MinPreState"); 92 93 // FormWindowState preState = (FormWindowState)myPropInfo.GetValue(tempForm, null); 94 // tempForm.WindowState = preState; 95 // } 96 // //激活窗体 97 // tempForm.Activate(); 98 // return true; 99 // } 100 //} 101 return false; 102 } 103 /// <summary>收到消息后 现在时子窗体中</summary> 104 delegate void invokeSetSubContent(DataInfo tempReceiveInfo); 105 void onSetSubContent(DataInfo tempReceiveInfo) 106 { 107 string subFormName = userInfoSplice(tempReceiveInfo); 108 string fromMachineName = Encoding.UTF8.GetString(tempReceiveInfo.FromMachineName); 109 string receiveMessage = Encoding.UTF8.GetString(tempReceiveInfo.Message); 110 Form tempForm = Application.OpenForms[subFormName]; 111 if (tempForm == null) 112 { 113 Chat_Dialog childForm = new Chat_Dialog(subFormName); 114 //dialogFrom childForm = new dialogFrom(subFormName); 115 childForm.ChildUdpClient = udpClient; 116 childForm.Show(); 117 118 Control ctl = childForm.Controls[0].Controls[0]; 119 string tempStr = ctl.ToString(); 120 foreach (Control subCtl in ctl.Controls) 121 { 122 if (subCtl.Name.Equals("displayTexBox")) 123 { 124 //string getOldMsg = ((RichTextBox)subCtl).Rtf; 125 ////处理好准备 加入新消息 126 //getOldMsg = getOldMsg.Substring(0, getOldMsg.LastIndexOf(@"\par")); 127 128 string header = fromMachineName + " " + tempReceiveInfo.Time; 129 //string getMsg = SetMessage(getOldMsg, header, receiveMessage, Color.Blue); 130 131 //((RichTextBox)subCtl).Rtf = getMsg; 132 SetMessage(header, receiveMessage, Color.Blue, ((RichTextBox)subCtl)); 133 //滚动条在下面 134 ((RichTextBox)subCtl).SelectionStart = ((RichTextBox)subCtl).Text.Length; 135 ((RichTextBox)subCtl).SelectionLength = 0; 136 ((RichTextBox)subCtl).ScrollToCaret(); 137 } 138 } 139 //激活窗体 140 childForm.Activate(); 141 } 142 else 143 { 144 Control ctl = tempForm.Controls[0].Controls[0]; 145 string tempStr = ctl.ToString(); 146 foreach (Control subCtl in ctl.Controls) 147 { 148 if (subCtl.Name.Equals("displayTexBox")) 149 { 150 //string getOldMsg = ((RichTextBox)subCtl).Rtf; 151 ////处理好准备 加入新消息 152 //getOldMsg = getOldMsg.Substring(0, getOldMsg.LastIndexOf(@"\par")); 153 154 string header = fromMachineName + " " + tempReceiveInfo.Time; 155 //string getMsg = SetMessage(getOldMsg, header, receiveMessage, Color.Blue); 156 157 //((RichTextBox)subCtl).Rtf = getMsg; 158 SetMessage(header, receiveMessage, Color.Blue, ((RichTextBox)subCtl)); 159 //滚动条在下面 160 ((RichTextBox)subCtl).SelectionStart = ((RichTextBox)subCtl).Text.Length; 161 ((RichTextBox)subCtl).SelectionLength = 0; 162 ((RichTextBox)subCtl).ScrollToCaret(); 163 } 164 } 165 //激活窗体 166 tempForm.Activate(); 167 } 168 169 170 171 /* 172 foreach (Form tempForm in Application.OpenForms) 173 { 174 //Aha...found it 175 if (tempForm.Text == subFormName) 176 { 177 Control ctl = tempForm.Controls[0].Controls[0]; 178 foreach (Control subCtl in ctl.Controls) 179 { 180 if (subCtl.Name.Equals("displayTexBox")) 181 { 182 //string getOldMsg = ((RichTextBox)subCtl).Rtf; 183 ////处理好准备 加入新消息 184 //getOldMsg = getOldMsg.Substring(0, getOldMsg.LastIndexOf(@"\par")); 185 186 string header = fromMachineName + " " + tempReceiveInfo.Time; 187 //string getMsg = SetMessage(getOldMsg, header, receiveMessage, Color.Blue); 188 189 //((RichTextBox)subCtl).Rtf = getMsg; 190 SetMessage(header, receiveMessage, Color.Blue, ((RichTextBox)subCtl)); 191 //滚动条在下面 192 ((RichTextBox)subCtl).SelectionStart = ((RichTextBox)subCtl).Text.Length; 193 ((RichTextBox)subCtl).SelectionLength = 0; 194 ((RichTextBox)subCtl).ScrollToCaret(); 195 } 196 } 197 //还原窗体 198 //tempForm.WindowState = FormWindowState.Normal; 199 //激活窗体 200 tempForm.Activate(); 201 } 202 } 203 */ 204 } 205 206 /// <summary>收到消息后 任务栏图标闪烁</summary> 207 delegate void invokeSetMinIconChange(bool states); 208 void onSetMinIconChange(bool states) 209 { 210 this.minPicChage.Enabled = states;//将定时控件设为启用,默认为false 211 } 212 213 /// <summary>对内容进行设置</summary> 214 public void SetMessage(string header, string body, Color color, RichTextBox mainRtb) 215 { 216 this.rtbHidden2.Rtf = mainRtb.Rtf; 217 this.rtbHidden3.Rtf = body; 218 //给每行内容加空格 219 //rtbHidden3.SelectAll(); 220 //rtbHidden3.SelectionIndent = 8; 221 222 223 StringBuilder sb = new StringBuilder(); 224 sb.Append(header); 225 sb.Append(Environment.NewLine); 226 //sb.Append(body); 227 //为了LastIndexOf(@"\par") 228 //sb.Append(Environment.NewLine); 229 230 rtbHidden.Clear(); 231 rtbHidden.Text = sb.ToString(); 232 rtbHidden.Select(0, header.Length); 233 rtbHidden.SelectionColor = color; 234 235 rtbHidden3.SelectionStart = 0; 236 rtbHidden3.SelectionLength = rtbHidden3.Text.Length; 237 238 rtbHidden2.SelectionStart = 0; 239 rtbHidden2.SelectionLength = rtbHidden2.Text.Length; 240 241 rtbHidden.SelectionStart = 0; 242 rtbHidden.SelectionLength = rtbHidden.Text.Length; 243 244 mainRtb.SelectionStart = 0; 245 mainRtb.SelectionLength = mainRtb.Text.Length; 246 247 mainRtb.SelectedRtf = rtbHidden2.SelectedRtf; 248 mainRtb.SelectionStart = mainRtb.Text.Length; 249 mainRtb.SelectionLength = 0; 250 mainRtb.SelectedText = "\n"; 251 mainRtb.SelectionStart = mainRtb.Text.Length; 252 mainRtb.SelectionLength = 0; 253 mainRtb.SelectedRtf = rtbHidden.SelectedRtf; 254 255 mainRtb.SelectionStart = mainRtb.Text.Length; 256 mainRtb.SelectionLength = 0; 257 mainRtb.SelectedRtf = rtbHidden3.SelectedRtf; 258 259 rtbHidden3.SelectionStart = 0; 260 rtbHidden3.SelectionLength = 0; 261 rtbHidden2.SelectionStart = 0; 262 rtbHidden2.SelectionLength = 0; 263 rtbHidden.SelectionStart = 0; 264 rtbHidden.SelectionLength = 0; 265 } 266 #endregion 267 268 private void Chat_Main_Load(object sender, EventArgs e) 269 { 270 #region 初始化设置 271 //主窗体在桌面边缘悬停 272 System.Windows.Forms.Timer StopRectTimer = new System.Windows.Forms.Timer(); 273 StopRectTimer.Tick += new EventHandler(likeQQFormStyle_Tick); 274 StopRectTimer.Interval = 50; 275 StopRectTimer.Enabled = true; 276 this.TopMost = true; 277 StopRectTimer.Start(); 278 279 //主窗体渐变效果 280 //定位窗体初始化位置 在屏幕的左下角 281 int x = Screen.PrimaryScreen.WorkingArea.Right - this.Width; 282 int y = Screen.PrimaryScreen.WorkingArea.Bottom - this.Height; 283 this.Location = new Point(x, y); 284 AnimateWindow(this.Handle, 1000, AW_HOR_POSITIVE | AW_ACTIVATE); 285 286 //为了信息转换使用 287 this.rtbHidden.Visible = false;//header 288 this.rtbHidden2.Visible = false;//历史记录 289 this.rtbHidden3.Visible = false;//新记录 290 this.minPicChage.Enabled = false;//将定时控件设为启用,默认为false 291 292 //显示内嵌图片 293 Assembly asm = Assembly.GetExecutingAssembly(); 294 string name = asm.GetName().Name; 295 Icon img = new Icon(asm.GetManifestResourceStream(name + ".Img.Application.ico")); 296 this.minIcon.Icon = img;//載入圖片資源 297 this.minIcon.Visible = true; 298 #endregion 299 udpClient = new UdpClient(PORT); 300 //广播地址 301 IPAddress groupAddress = IPAddress.Parse(BROADCAST_ADDRESS); 302 //取得IP地址及端口 303 IPEndPoint ipEndPoint = new IPEndPoint(groupAddress, PORT); 304 305 //初始化计算机名和端口 306 IPHostEntry myEntry = Dns.GetHostEntry(Dns.GetHostName()); 307 IPAddress myAddress = new IPAddress(myEntry.AddressList[0].Address); 308 309 //获取本地信息 310 LocalInfo = new DataInfo(); 311 LocalInfo.CommandFlag = COMMAND_FLAG_REFRESH; 312 LocalInfo.FromMachineIp = myAddress.ToString(); 313 LocalInfo.FromMachineName = Encoding.UTF8.GetBytes(Dns.GetHostName()); 314 LocalInfo.ToMachineIp = groupAddress.ToString(); 315 LocalInfo.Time = string.Empty; 316 LocalInfo.SubFormName = Encoding.UTF8.GetBytes(string.Empty); 317 LocalInfo.Message = Encoding.UTF8.GetBytes(string.Empty); 318 319 runing = true; 320 //开启监听线程 321 base.baseThread = new Thread(new ThreadStart(this.listenPort)); 322 base.baseThread.Start(); 323 324 sendPack(LocalInfo); 325 } 326 327 bool runing = false; 328 #region 局域网侦听 329 /// <summary> 330 /// 侦听指定端口的广播地址UDP包 331 /// </summary> 332 private void listenPort() 333 { 334 #region 队列消息模式 335 /* 336 System.Messaging.MessageQueue msgQueue = new MessageQueue(); 337 //新建一个系统消息对象; 338 System.Messaging.Message msg = new System.Messaging.Message(); 339 if (Application.OpenForms.Count != 1) 340 { 341 string path = @"web000\private$\msmqdemo"; 342 343 //新建一个消息队列对象,与服务路径相链接(一定要与发送时使用的路径全一样); 344 msgQueue = new MessageQueue(path); 345 346 if (MessageQueue.Exists(path)) 347 { 348 msgQueue = new MessageQueue(path); 349 } 350 else 351 { 352 msgQueue = MessageQueue.Create(path); 353 } 354 355 } 356 IPEndPoint tempEnd = new IPEndPoint(IPAddress.Any, 2525); 357 while (true) 358 { 359 Application.DoEvents(); 360 byte[] bytesF = base.udpClient.Receive(ref tempEnd); 361 if (Application.OpenForms.Count == 1) 362 { 363 #region 不分包接收 364 365 //byte[] recb = base.udpClient.Receive(ref tempEnd); 366 // 检查所接收到的信息 367 checkMessage(bytesF); 368 369 #endregion 370 } 371 else 372 { 373 try 374 { 375 System.Threading.Thread.Sleep(1000); 376 //接收一条队列的信息;本次接收动作的持续时间为10秒; 377 msg = msgQueue.Receive(new TimeSpan(0, 0, 0, 10)); 378 msg.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) }); 379 if (msg != null) 380 { 381 byte[] bytes = (byte[])msg.Body; 382 //给控件赋值,便于查看 383 //setValue(msg.Body.ToString()); 384 } 385 } 386 catch 387 { 388 System.Threading.Thread.Sleep(5000); 389 } 390 msg.Dispose(); 391 msgQueue.Dispose(); 392 } 393 } 394 * */ 395 #endregion 396 397 #region 监听模式 398 IPEndPoint tempEnd = new IPEndPoint(IPAddress.Any, 2525); 399 while (runing) 400 { 401 Application.DoEvents(); 402 try 403 { 404 byte[] bytesF = base.udpClient.Receive(ref tempEnd); 405 if (Application.OpenForms.Count == 1) 406 { 407 #region 不分包接收 408 409 //byte[] recb = base.udpClient.Receive(ref tempEnd); 410 // 检查所接收到的信息 411 checkMessage(bytesF); 412 413 #endregion 414 } 415 else 416 { 417 #region 分包接收 418 int m_intBlockLength = 1400; 419 //byte[] bytesF = base.udpClient.Receive(ref tempEnd); 420 421 int m_intSerial = 0; 422 int m_intBlocks = 0; //数据分割块数 423 int m_intLength = 0; //数据长度 424 int m_intMessageLength = 0; 425 int place = 0; 426 int m_intGetCount = 0; 427 //发送方ip 428 string m_stringIP = string.Empty; 429 //发送时间 430 string m_stringNow = string.Empty; 431 432 place = 0; 433 m_stringIP = Encoding.ASCII.GetString(bytesF, place, 15); 434 place += 15; 435 m_stringNow = Encoding.ASCII.GetString(bytesF, place, 8); 436 place += 8; 437 m_intSerial = BitConverter.ToInt32(bytesF, place);//顺序戳 438 place += 4; 439 m_intBlocks = BitConverter.ToInt32(bytesF, place);//数据总块数 440 place += 4; 441 m_intLength = BitConverter.ToInt32(bytesF, place);//数据长度 442 place += 4; 443 m_intMessageLength = BitConverter.ToInt32(bytesF, place);//数据总长度 444 place += 4; 445 446 byte[] data = new byte[m_intMessageLength]; //申明数据的总长 447 448 Array.Copy(bytesF, 15 + 8 + 16, data, m_intBlockLength * m_intSerial, m_intLength); //复制数据 449 450 m_intGetCount = m_intGetCount + 1; 451 Application.DoEvents(); 452 453 if (m_intBlocks > 1) 454 { 455 while (true) 456 { 457 byte[] bytes = base.udpClient.Receive(ref tempEnd); 458 459 place = 0; 460 m_stringIP = Encoding.UTF8.GetString(bytes, place, 15); 461 place += 15; 462 m_stringNow = Encoding.UTF8.GetString(bytes, place, 8); 463 place += 8; 464 m_intSerial = BitConverter.ToInt32(bytes, place);//顺序戳 465 place += 4; 466 m_intBlocks = BitConverter.ToInt32(bytes, place);//数据总块数 467 place += 4; 468 m_intLength = BitConverter.ToInt32(bytes, place);//数据长度 469 place += 4; 470 m_intMessageLength = BitConverter.ToInt32(bytes, place);//数据总长度 471 place += 4; 472 473 Array.Copy(bytes, 15 + 8 + 16, data, m_intBlockLength * m_intSerial, m_intLength); //复制数据 474 475 m_intGetCount = m_intGetCount + 1; 476 477 Application.DoEvents(); 478 //取得块数 >= 数据总块数 479 if (m_intGetCount >= m_intBlocks) 480 { 481 break; 482 } 483 } 484 } 485 486 DataInfo ReceiveInfo = (DataInfo)Chat_CommonClass.ByteAToObject(data); 487 // 检查所接收到的信息 488 checkMessage(data); 489 //string message = System.Text.Encoding.Default.GetString(data, 0, data.Length); 490 #endregion 491 } 492 } 493 catch (Exception e) 494 { 495 runing = false; 496 MessageBox.Show(e.Message.ToString()); 497 base.baseThread = new Thread(new ThreadStart(this.listenPort)); 498 base.baseThread.Start(); 499 break; 500 } 501 } 502 udpClient.Close(); 503 #endregion 504 } 505 506 /// <summary> 发送数据包到广播地址</summary> 507 private void sendPack(DataInfo tempDataInfo) 508 { 509 //Encoding.UTF8防止乱码 510 byte[] sendb = Chat_CommonClass.ObjectToByteA(tempDataInfo); 511 IPAddress tempAddress = IPAddress.Parse(tempDataInfo.ToMachineIp); 512 IPEndPoint tempIpEndPoint = new IPEndPoint(tempAddress, PORT); 513 try 514 { 515 base.udpClient.Send(sendb, sendb.Length, tempIpEndPoint); 516 } 517 catch (Exception e) 518 { 519 MessageBox.Show(e.Message.ToString()); 520 } 521 } 522 523 /// <summary>操作接收的数据包</summary> 524 private void checkMessage(byte[] recbb) 525 { 526 ReceiveInfo = new DataInfo(); 527 ReceiveInfo = (DataInfo)Chat_CommonClass.ByteAToObject(recbb); 528 switch (ReceiveInfo.CommandFlag) 529 { 530 case COMMAND_FLAG_REFRESH: 531 //本机上线通知 532 if (ReceiveInfo.ToMachineIp.Equals(BROADCAST_ADDRESS) && LocalInfo.FromMachineIp.Equals(ReceiveInfo.FromMachineIp)) 533 { 534 //如果不存在则添加该用户 535 if (userListTable.FindString(userInfoSplice(ReceiveInfo)) <= 0) 536 { 537 //操作用户列表 538 Invoke(new invokeSetUserList(onSetUserList), ReceiveInfo, LIST_TYPE_ADD); 539 } 540 } 541 else if (ReceiveInfo.ToMachineIp.Equals(BROADCAST_ADDRESS) && !LocalInfo.FromMachineIp.Equals(ReceiveInfo.FromMachineIp)) 542 { 543 LocalInfo.CommandFlag = COMMAND_FLAG_REFRESH; 544 LocalInfo.ToMachineIp = ReceiveInfo.FromMachineIp; 545 LocalInfo.Time = string.Empty; 546 LocalInfo.SubFormName = Encoding.UTF8.GetBytes(string.Empty); 547 LocalInfo.Message = Encoding.UTF8.GetBytes(string.Empty); 548 //从其他机器发送过来的刷新请求 549 //返回自己的信息 550 sendPack(LocalInfo); 551 552 //如果不存在则添加该用户 553 if (userListTable.FindString(userInfoSplice(ReceiveInfo)) <= 0) 554 { 555 //操作用户列表 556 Invoke(new invokeSetUserList(onSetUserList), ReceiveInfo, LIST_TYPE_ADD); 557 } 558 } 559 else if (ReceiveInfo.ToMachineIp.Equals(LocalInfo.FromMachineIp)) 560 { 561 //如果不存在则添加该用户 562 if (userListTable.FindString(userInfoSplice(ReceiveInfo)) <= 0) 563 { 564 //操作用户列表 565 Invoke(new invokeSetUserList(onSetUserList), ReceiveInfo, LIST_TYPE_ADD); 566 } 567 } 568 569 break; 570 case COMMAND_FLAG_CHAT: 571 string childFormName = Encoding.UTF8.GetString(ReceiveInfo.SubFormName); 572 573 //取得发给自己的信息 574 if (LocalInfo.FromMachineIp.Equals(ReceiveInfo.ToMachineIp)) 575 { 576 Invoke(new invokeSetSubContent(onSetSubContent), ReceiveInfo); 577 } 578 break; 579 case COMMAND_FLAG_CLOSE: 580 //从其他机器发送过来的刷新请求 581 if(!ReceiveInfo.FromMachineIp.Equals(LocalInfo.FromMachineIp)) 582 { 583 //如果存在则删除该用户 584 if (userListTable.FindString(userInfoSplice(ReceiveInfo)) > 0) 585 { 586 //操作用户列表 587 Invoke(new invokeSetUserList(onSetUserList), ReceiveInfo, LIST_TYPE_DEL); 588 } 589 } 590 break; 591 default: 592 break; 593 } 594 } 595 #endregion 596 597 /// <summary>拼接 用户名+IP</summary> 598 private string userInfoSplice(DataInfo tempGetInfo) 599 { 600 string hostName = Encoding.UTF8.GetString(tempGetInfo.FromMachineName); 601 string hostIp = tempGetInfo.FromMachineIp; 602 StringBuilder returnValue = new StringBuilder(); 603 if (!(string.Empty.Equals(hostName) || string.Empty.Equals(hostIp))) 604 { 605 returnValue.Append(hostName); 606 returnValue.Append("("); 607 returnValue.Append(hostIp); 608 returnValue.Append(")"); 609 } 610 611 return returnValue.ToString(); 612 } 613 614 /// <summary>分解 用户名+IP</summary> 615 private DataInfo userInfoSeparate(string tempAllStr) 616 { 617 //分解 取得 Ip 和 主机名 618 string[] ipGroup = tempAllStr.ToString().Split('('); 619 string ip = ipGroup[1].Substring(0, ipGroup[1].Length - 1); 620 string host = ipGroup[0]; 621 622 DataInfo getInfo = new DataInfo(); 623 getInfo.FromMachineIp = ip; 624 getInfo.FromMachineName = Encoding.UTF8.GetBytes(host); 625 626 return getInfo; 627 } 628 629 /// <summary> 630 /// 判断子窗体时候已经存在 631 /// </summary> 632 /// <param name="name"></param> 633 /// <returns></returns> 634 private bool isHasSameChild(string formName) 635 { 636 return (bool)Invoke(new invokeFormIsExist(formIsExist), formName); 637 } 638 639 private void userListTable_MouseDoubleClick(object sender, MouseEventArgs e) 640 { 641 //用构造函数传值 642 if (userListTable.SelectedItem != null) 643 { 644 string childFormName = userListTable.SelectedItem.ToString(); 645 DataInfo sendInfoToChild = userInfoSeparate(childFormName); 646 //检验该用户的窗体是否打开 647 if (!isHasSameChild(childFormName)) 648 { 649 int formCount = Application.OpenForms.Count - 1; 650 Chat_Dialog childForm = new Chat_Dialog(childFormName); 651 childForm.ChildUdpClient = udpClient; 652 childForm.Show(); 653 } 654 } 655 } 656 657 private void Chat_Main_FormClosing(object sender, FormClosingEventArgs e) 658 { 659 //关闭循环 660 runing = false; 661 base.baseThread.IsBackground = true; 662 base.baseThread.Abort(); 663 } 664 665 /// <summary> 任务栏 单机鼠标右健出现菜单 </summary> 666 private void minIcon_MouseClick(object sender, MouseEventArgs e) 667 { 668 // 鼠标右击才会触发contextMenuStrip控件, 669 if (e.Button == MouseButtons.Right) 670 { 671 this.minIconContextMenuStrip.Show(MousePosition); 672 } 673 } 674 675 private void refesh_Click(object sender, EventArgs e) 676 { 677 this.userListTable.Items.Clear(); 678 //广播地址 679 IPAddress groupAddress = IPAddress.Parse(BROADCAST_ADDRESS); 680 //取得IP地址及端口 681 IPEndPoint ipEndPoint = new IPEndPoint(groupAddress, PORT); 682 683 //初始化计算机名和端口 684 IPHostEntry myEntry = Dns.GetHostEntry(Dns.GetHostName()); 685 IPAddress myAddress = new IPAddress(myEntry.AddressList[0].Address); 686 687 //获取本地信息 688 LocalInfo = new DataInfo(); 689 LocalInfo.CommandFlag = COMMAND_FLAG_REFRESH; 690 LocalInfo.FromMachineIp = myAddress.ToString(); 691 LocalInfo.FromMachineName = Encoding.UTF8.GetBytes(Dns.GetHostName()); 692 LocalInfo.ToMachineIp = groupAddress.ToString(); 693 LocalInfo.Time = string.Empty; 694 LocalInfo.SubFormName = Encoding.UTF8.GetBytes(string.Empty); 695 LocalInfo.Message = Encoding.UTF8.GetBytes(string.Empty); 696 697 sendPack(LocalInfo); 698 } 699 700 /// <summary>关闭程序</summary> 701 private void menuItem_Exit_Click(object sender, EventArgs e) 702 { 703 DialogResult result; 704 result = MessageBox.Show(this, "你确定要退出JToolDemo吗?", "JToolDemo...", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); //"簡訊勤務兵..." 705 if (result == DialogResult.OK) 706 { 707 //关闭循环 708 runing = false; 709 710 LocalInfo.CommandFlag = COMMAND_FLAG_CLOSE; 711 LocalInfo.ToMachineIp = BROADCAST_ADDRESS; 712 LocalInfo.Time = string.Empty; 713 LocalInfo.SubFormName = Encoding.UTF8.GetBytes(string.Empty); 714 LocalInfo.Message = Encoding.UTF8.GetBytes(string.Empty); 715 //从其他机器发送过来的刷新请求 716 //返回自己的信息 717 sendPack(LocalInfo); 718 //base.baseThread.IsBackground = true; 719 //base.baseThread.Abort(); 720 this.Dispose(); 721 this.Close(); 722 } 723 } 724 725 int i = 0; 726 /// <summary>任务栏图标闪烁</summary> 727 private void minPicChage_Tick(object sender, EventArgs e) 728 { 729 Assembly asm = Assembly.GetExecutingAssembly(); 730 string name = asm.GetName().Name; 731 Icon ico2 = new Icon(asm.GetManifestResourceStream(name + ".Img.Application.ico")); 732 Icon ico1 = new Icon(asm.GetManifestResourceStream(name + ".Img.qq.ico")); 733 734 //如果i=0则让任务栏图标变为透明的图标并且退出 735 if (i < 1) 736 { 737 this.minIcon.Icon = ico2; 738 i++; 739 return; 740 } 741 //如果i!=0,就让任务栏图标变为ico1,并将i置为0; 742 else 743 { 744 this.minIcon.Icon = ico1; 745 } 746 i = 0; 747 } 748 749 #region 桌面边缘悬停 750 751 /// <summary>桌面边缘悬停</summary> 752 private void likeQQFormStyle_Tick(object sender, EventArgs e) 753 { 754 if (this.Bounds.Contains(System.Windows.Forms.Cursor.Position)) 755 { 756 switch (this.StopAanhor) 757 { 758 case AnchorStyles.Top: 759 this.Location = new Point(this.Location.X, 0); 760 break; 761 case AnchorStyles.Left: 762 this.Location = new Point(0, this.Location.Y); 763 break; 764 case AnchorStyles.Right: 765 this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - this.Width, this.Location.Y); 766 break; 767 //注释在底部的时候 找不到了 有Bug 768 //case AnchorStyles.Bottom: 769 // this.Location = new Point(this.Location.X, Screen.PrimaryScreen.Bounds.Height - this.Height); 770 // break; 771 } 772 } 773 else 774 { 775 switch (this.StopAanhor) 776 { 777 case AnchorStyles.Top: 778 this.Location = new Point(this.Location.X, (this.Height - 8) * (-1)); 779 break; 780 case AnchorStyles.Left: 781 this.Location = new Point((-1) * (this.Width - 8), this.Location.Y); 782 break; 783 case AnchorStyles.Right: 784 this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - 8, this.Location.Y); 785 break; 786 //注释在底部的时候 找不到了 有Bug 787 //case AnchorStyles.Bottom: 788 // this.Location = new Point(this.Location.X, (Screen.PrimaryScreen.Bounds.Height - 8)); 789 // break; 790 } 791 } 792 } 793 794 internal AnchorStyles StopAanhor = AnchorStyles.None; 795 private void mStopAnhor() 796 { 797 if (this.Top <= 0 && this.Left <= 0) 798 { 799 StopAanhor = AnchorStyles.None; 800 } 801 else if (this.Top <= 0) 802 { 803 StopAanhor = AnchorStyles.Top; 804 } 805 else if (this.Left <= 0) 806 { 807 StopAanhor = AnchorStyles.Left; 808 } 809 else if (this.Left >= Screen.PrimaryScreen.Bounds.Width - this.Width) 810 { 811 StopAanhor = AnchorStyles.Right; 812 } 813 else if (this.Top >= Screen.PrimaryScreen.Bounds.Height - this.Height) 814 { 815 StopAanhor = AnchorStyles.Bottom; 816 } 817 else 818 { 819 StopAanhor = AnchorStyles.None; 820 } 821 } 822 823 private void Chat_Main_LocationChanged(object sender, EventArgs e) 824 { 825 this.mStopAnhor(); 826 } 827 #endregion 828 829 #region 主窗体渐变效果 830 //API原型 831 [DllImport("user32.dll")] 832 private static extern bool AnimateWindow(IntPtr hwnd, int dateTime, int dwFlags);//hwnd窗口句柄.dateTime:动画时长.dwFlags:动画类型组合 833 int AW_ACTIVE = 0x20000; //激活窗口,在使用了AW_HIDE标志后不要使用这个标志 834 int AW_HIDE = 0x10000;//隐藏窗口 835 int AW_BLEND = 0x80000;// 使用淡入淡出效果 836 int AW_SLIDE = 0x40000;//使用滑动类型动画效果,默认为滚动动画类型,当使用AW_CENTER标志时,这个标志就被忽略 837 int AW_CENTER = 0x0010;//若使用了AW_HIDE标志,则使窗口向内重叠;否则向外扩展 838 int AW_HOR_POSITIVE = 0x0001;//自左向右显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志 839 int AW_HOR_NEGATIVE = 0x0002;//自右向左显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志 840 int AW_VER_POSITIVE = 0x0004;//自顶向下显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志 841 int AW_VER_NEGATIVE = 0x0008;//自下向上显示窗口,该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志 842 const int AW_ACTIVATE = 0x20000; 843 #endregion 844 } 845 }


关于取得IP代码过期的问题
- privatevoid GetIP()
- {
- string hostName = Dns.GetHostName();//本机名
- //System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期,我运行时且只返回了一个IPv4的地址
- System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//会返回所有地址,包括IPv4和IPv6
- foreach (IPAddress ip in addressList)
- {
- listBox1.Items.Add(ip.ToString());
- }
- //IPv6 addressList[5]是IP
- }

浙公网安备 33010602011771号