我有以下代码可以使用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");
}
}
一开始,我调用registerLanListener,在停止我的应用程序之前,我调用unregisterLanListener()。我已经在win7和win8平板电脑上测试了我的桌面应用程序,多次连接/断开wifi连接并尝试观察通知。这两个平台都存在以下问题:
大多数情况下,我的wlanconnectionchangehandler在wifi连接/断开连接时被调用,一切正常。然而,在某些情况下,它根本不会被调用。什么会导致这种情况?我注意到,在最初的错过通知之后,即使我继续连接/断开WiFi连接,我也无法收到任何进一步的通知。
在不同的情况下,即使我删除了事件处理程序,我仍然会收到通知。删除这些事件处理程序时是否遗漏了某些内容?
谢谢您。
最佳答案
很明显我在编码的时候没有想清楚。问题是我的wlanclient客户机的本地范围。通过将其设为全局变量并只实例化一次来修复它。/脸谱