我有以下代码使用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连接,我也无法收到任何进一步的通知。
在不同的场合,即使我删除了事件处理程序,我仍然会收到通知。我在删除这些事件处理程序时遗漏了什么吗?
谢谢。
答案 0 :(得分:0)
显然,当我编码时,我并没有想清楚。问题是我的WlanClient客户端的本地范围。通过使其成为全局变量并仅将其实例化一次来修复它。 /捂脸