C#窗体程序,点击按钮通过MAC地址远程网络唤醒电脑主机的完整代码
时间: 2024-09-14 19:10:28 浏览: 40
在C#中创建一个Windows Forms应用程序,通过MAC地址远程唤醒计算机需要使用到Wolfram(Wake On LAN,即通过发送特定的数据包来启动计算机)。以下是一个简单的示例代码,假设你已经安装了`System.Net.NetworkInformation`命名空间所需的库,并且获取MAC地址和IP地址的方式已设定好:
```csharp
using System;
using System.Net;
using System.Net.NetworkInformation;
public partial class Form1 : Form
{
private static readonly string[] MagicPacket = { 0xFF, 0xD8, 0x64, 0x00, 0x01, 0x00, 0x00, 0x00, 0x5A, 0x90, 0x67, 0x6F, 0x7B, 0x0D, 0x0D, 0x11, 0x8C, 0xA2, 0x37, 0x00, 0x00 };
public Form1()
{
InitializeComponent();
button1.Click += Button1_Click;
}
private void Button1_Click(object sender, EventArgs e)
{
// 替换为你实际的MAC地址
string macAddress = "01:23:45:67:89:ab"; // e.g., "AA:BB:CC:DD:EE:FF"
try
{
byte[] ipBytes = IPAddress.Parse("192.168.1.255").GetAddressBytes(); // 远程唤醒目标IP地址
byte[] packet = new byte[ipBytes.Length + MagicPacket.Length];
Array.Copy(ipBytes, 0, packet, 0, ipBytes.Length);
Array.Copy(MagicPacket, 0, packet, ipBytes.Length, MagicPacket.Length);
using (UdpClient client = new UdpClient())
{
client.Send(packet, packet.Length, IPAddress.Broadcast, 9); // 发送广播到255.255.255.255(UDP端口9)
MessageBox.Show("Magic Packet Sent to唤醒目标计算机");
}
}
catch (Exception ex)
{
MessageBox.Show($"Error sending Magic Packet: {ex.Message}");
}
}
}
阅读全文