使用来自此链接的此代码示例(这里也提到了这个问题)。
public partial class MyClient : UserControl
{
public MyClient()
{
MACAddressManager macAddressManager = new MACAddressManager();
macAddressManager.OnGetMACAddressCompleted += new EventHandler(macAddressManager_OnGetMACAddressCompleted);
macAddressManager.BeginGetMACAddress();
}
void macAddressManager_OnGetMACAddressCompleted(object sender, EventArgs e)
{
MACAddressManager manager = (MACAddressManager) sender;
// MAC Address value is in manager.MACAddress
}
}
public class MACAddressManager
{
private dynamic sWbemServices;
private dynamic sWbemSink;
public string MACAddress { get; private set; }
public event EventHandler OnGetMACAddressCompleted;
private void EndGetMACAddress(object sender, EventArgs e)
{
dynamic objWbemObject = sender;
MACAddress = objWbemObject.MACAddress;
if (OnGetMACAddressCompleted != null)
OnGetMACAddressCompleted(this, EventArgs.Empty);
}
public void BeginGetMACAddress()
{
if ((Application.Current.IsRunningOutOfBrowser) && (Application.Current.HasElevatedPermissions) && (AutomationFactory.IsAvailable))
{
dynamic sWbemLocator = AutomationFactory.CreateObject("WbemScripting.SWBemLocator");
sWbemServices = sWbemLocator.ConnectServer(".");
sWbemServices.Security_.ImpersonationLevel = 3; //impersonate
sWbemSink = AutomationFactory.CreateObject("WbemScripting.SWbemSink");
sWbemSink.OnObjectReady += new EventHandler(EndGetMACAddress);
string query = "SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true";
sWbemServices.ExecQueryAsync(sWbemSink, query);
}
}
}