C#窗体程序,点击按钮通过MAC地址远程TCP协议网络唤醒电脑主机的完整代码
时间: 2024-09-14 17:10:30 浏览: 46
c# 远程网络唤醒电脑(远程开机),源码+发布好的绿色版程序
在C#中,通过按钮点击实现MAC地址的远程TCP唤醒计算机主机涉及到几个关键步骤,包括网络连接、发送数据以及操作系统级别的命令执行。由于Windows API提供了用于远程控制的功能,我们可以使用`ManagementObjectSearcher`来发送Wake-on-LAN信号。以下是一个简化的示例代码片段,注意这只是一个基础的框架,并未包含完整的错误处理和异常管理:
```csharp
using System;
using System.Management;
using System.Net.NetworkInformation;
public partial class Form1 : Form
{
private static readonly byte[] MagicPacket = new byte[6] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xd0 };
private void buttonSend_Click(object sender, EventArgs e)
{
string ipAddress = "your_computer_ip_address";
if (string.IsNullOrEmpty(ipAddress))
return;
// 获取目标设备的MAC地址
ManagementObjectSearcher searcher = new ManagementObjectSearcher($"select * from Win32_NetworkAdapterConfiguration where IPAddress='{ipAddress}'");
ManagementObject targetAdapter = searcher.Get()[0];
string macAddress = targetAdapter.Properties["MacAddress"].Value.ToString();
try
{
// 构建魔力包(针对特定MAC地址)
foreach (byte b in macAddress.HexToByteArray())
MagicPacket[5] = b;
// 连接到服务器端并发送数据
using (TcpClient client = new TcpClient())
{
client.Connect(ipAddress, 9);
NetworkStream stream = client.GetStream();
stream.Write(MagicPacket, 0, MagicPacket.Length);
stream.Close();
client.Close();
MessageBox.Show("Wake-on-LAN signal sent to the specified computer.");
}
}
catch (Exception ex)
{
MessageBox.Show($"Failed to send Wake-on-LAN: {ex.Message}");
}
}
}
阅读全文