C#,窗体程序,接收到UDP数据“shutdown”,程序一分钟后关闭,然后再关闭电脑主机的完整代码
时间: 2024-09-20 08:05:40 浏览: 47
在C#中,创建一个简单的Windows Forms应用程序接收UDP数据,并在接收到特定数据(比如"shutdown")后延迟一分钟关闭,你可以按照以下步骤编写:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Timers;
public partial class MainForm : Form
{
private UdpClient udpClient;
private Timer shutdownTimer;
public MainForm()
{
InitializeComponent();
InitializeUdpClient();
}
private void InitializeUdpClient()
{
udpClient = new UdpClient(YourPortNumber); // 替换为你要监听的端口号
shutdownTimer = new Timer(60 * 1000); // 创建一个计时器,延迟一分钟
shutdownTimer.Elapsed += ShutdownHandler;
shutdownTimer.Enabled = false; // 初始状态禁用
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
BeginReceive();
}
catch (SocketException ex)
{
MessageBox.Show("Error initializing UDP client: " + ex.Message);
}
}
private void BeginReceive()
{
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
udpClient.BeginReceive(ref remoteEP, 0, 1024, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
private void ReceiveCallback(IAsyncResult ar)
{
byte[] bytes = udpClient.EndReceive(ar, ref remoteEP);
string dataReceived = Encoding.ASCII.GetString(bytes);
if (dataReceived.ToLower() == "shutdown") // 检查是否接收到"shutdown"数据
{
shutdownTimer.Start(); // 开始倒计时
}
}
private void ShutdownHandler(object sender, ElapsedEventArgs e)
{
Application.Exit(); // 应用程序即将退出,关闭窗口
Environment.Exit(0); // 关闭整个进程
}
}
//
阅读全文