我有以下代码来使用 managedWifi api (http://managedwifi.codeplex.com/) 监听 wifi 连接/断开事件
public void wlanConnectionChangeHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData){
string msg = String.Empty;
switch (notifyData.notificationSource)
{
case Wlan.WlanNotificationSource.ACM:
switch ((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode)
{
case Wlan.WlanNotificationCodeAcm.ConnectionStart:
msg = "ConnectionStart";
break;
case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
msg = "ConnectionComplete";
WlanClient client = new WlanClient();
foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
{
Wlan.WlanAssociationAttributes conAttributes = wlanIface.CurrentConnection.wlanAssociationAttributes;
Wlan.Dot11Ssid ssid = conAttributes.dot11Ssid;
PhysicalAddress bssid = conAttributes.Dot11Bssid;
int rssi = wlanIface.RSSI;
msg += ". ssid: " + GetStringForSSID(ssid) + ". rssi: " + rssi.ToString() + ". MAC: " + bssid.ToString();
break;
}
break;
case Wlan.WlanNotificationCodeAcm.Disconnecting:
msg = "Disconnecting";
break;
case Wlan.WlanNotificationCodeAcm.Disconnected:
msg = "Disconnected";
break;
default:
msg = "unknown notificationCode =" + notifyData.notificationCode;
break;
}
MessageBox.Show(msg + " for profile:" + connNotifyData.profileName);
break;
default:
//MessageBox.Show("irrelevant notification. Ignore");
break;
}
}
static string GetStringForSSID(Wlan.Dot11Ssid ssid)
{
return Encoding.ASCII.GetString( ssid.SSID, 0, (int) ssid.SSIDLength );
}
private void registerWlanListener()
{
WlanClient client = new WlanClient();
foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
{
string str = "Name=" + wlanIface.InterfaceName + ". State: ";
switch (wlanIface.InterfaceState)
{
case Wlan.WlanInterfaceState.NotReady:
str += "NotReady";
break;
case Wlan.WlanInterfaceState.Disconnected:
str += "Disconnected";
break;
case Wlan.WlanInterfaceState.Disconnecting:
str += "Disconnecting";
break;
case Wlan.WlanInterfaceState.Connected:
str += "Connected";
break;
}
wlanIface.WlanConnectionNotification += wlanConnectionChangeHandler;
MessageBox.Show(str + ". Listener registered");
}
}
private void unregisterWlanListener()
{
WlanClient client = new WlanClient();
foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
{
wlanIface.WlanConnectionNotification -= wlanConnectionChangeHandler;
MessageBox.Show(wlanIface.InterfaceName + ". Listener unregistered");
}
}
一开始,我调用 registerWlanListener,在停止我的应用程序之前,我调用 unregisterWlanListener()。我通过多次连接/断开wifi连接并尝试观察通知,在win7和win8平板电脑上测试了我的桌面应用程序。这些是两个平台上的问题:
大多数时候,我的 wlanConnectionChangeHandler 在 wifi 连接/断开时被调用,一切正常。但是,在某些情况下,它根本不会被调用。什么会导致这种情况?我注意到在最初错过的通知之后,即使我继续连接/断开 wifi 连接,我也根本无法收到任何进一步的通知。
在不同的情况下,即使我删除了事件处理程序,我仍然会收到通知。我在删除这些事件处理程序时遗漏了什么吗?
谢谢你。