接收客户端信息后右下角弹窗提示
时间: 2023-08-12 18:04:46 浏览: 65
要在接收到客户端信息后在右下角弹窗提示,你可以使用 Windows Forms 的 NotifyIcon 类和 ContextMenuStrip 类来实现。下面是一个示例代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
class TcpServer
{
private TcpListener server;
private TcpClient client;
private NetworkStream stream;
private byte[] buffer = new byte[1024];
private NotifyIcon notifyIcon;
public void StartServer()
{
// 创建 NotifyIcon
notifyIcon = new NotifyIcon();
notifyIcon.Icon = SystemIcons.Information;
notifyIcon.Visible = true;
// 创建 ContextMenuStrip
ContextMenuStrip contextMenu = new ContextMenuStrip();
ToolStripMenuItem exitItem = new ToolStripMenuItem("退出");
exitItem.Click += ExitItem_Click;
contextMenu.Items.Add(exitItem);
notifyIcon.ContextMenuStrip = contextMenu;
// 启动服务器
server = new TcpListener(IPAddress.Any, 1234);
server.Start();
// 接受客户端连接
client = server.AcceptTcpClient();
// 获取网络流
stream = client.GetStream();
// 开始异步读取数据
stream.BeginRead(buffer, 0, buffer.Length, OnDataReceived, null);
}
private void OnDataReceived(IAsyncResult result)
{
try
{
// 结束异步读取
int bytesRead = stream.EndRead(result);
if (bytesRead > 0)
{
// 处理接收到的数据
string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
// 显示系统通知
notifyIcon.BalloonTipTitle = "收到新消息";
notifyIcon.BalloonTipText = receivedData;
notifyIcon.ShowBalloonTip(3000);
// 清空缓冲区
Array.Clear(buffer, 0, buffer.Length);
// 继续异步读取数据
stream.BeginRead(buffer, 0, buffer.Length, OnDataReceived, null);
}
}
catch (Exception ex)
{
// 处理异常
MessageBox.Show("接收数据发生错误:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ExitItem_Click(object sender, EventArgs e)
{
// 退出程序
notifyIcon.Visible = false;
Application.Exit();
}
}
```
这个示例代码会在接收到客户端信息后,在系统的右下角弹出一个通知框来显示接收到的消息。你可以根据需要进行修改和扩展。记得在程序退出时调用 `notifyIcon.Visible = false;` 来隐藏 NotifyIcon,并确保在退出时调用 `Application.Exit();` 来关闭应用程序。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)