在紧凑框架中检测“网络电缆未连接”的方法

5

我已经查看了所有Stack Overflow的答案,但Google和Bing都没有给我任何帮助。我需要知道如何从一个Compact Framework应用程序中检测Windows CE设备的网络电缆连接或断开情况。

1个回答

3

我知道我在回答自己的问题,但实际上这是通过电子邮件问我的问题,我花了很长时间找到答案,所以我在这里发布它。

因此,如何检测到这个问题的一般答案是,您必须通过IOCTL调用进入NDIS驱动程序,并告诉它您对通知感兴趣。这是使用IOCTL_NDISUIO_REQUEST_NOTIFICATION值完成的(文档说这在WinMo中不受支持,但文档是错误的)。当然,接收通知并不那么简单-您不会只得到一些漂亮的回调。相反,您必须启动一个点对点消息队列,并将其发送到IOCTL调用中,以及您想要的特定通知的掩码。然后,当某些内容发生更改(例如拔出电缆)时,您将在队列上收到一个NDISUIO_DEVICE_NOTIFICATION结构体(再次,MSDN错误地说这仅适用于CE),您可以解析该结构体以查找具有事件的适配器以及确切的事件。

从托管代码的角度来看,这实际上是需要编写的大量代码-使用CreateFile打开NDIS,所有队列API,通知结构等。幸运的是,我已经走过这条路,并已将其添加到了智能设备框架中。因此,如果您正在使用SDF,则获取通知的方法如下:

public partial class TestForm : Form
{
    public TestForm()
    {
        InitializeComponent();

        this.Disposed += new EventHandler(TestForm_Disposed);

        AdapterStatusMonitor.NDISMonitor.AdapterNotification += 
            new AdapterNotificationEventHandler(NDISMonitor_AdapterNotification);
        AdapterStatusMonitor.NDISMonitor.StartStatusMonitoring();
    }

    void TestForm_Disposed(object sender, EventArgs e)
    {
        AdapterStatusMonitor.NDISMonitor.StopStatusMonitoring();
    }

    void NDISMonitor_AdapterNotification(object sender, 
                                         AdapterNotificationArgs e)
    {
        string @event = string.Empty;

        switch (e.NotificationType)
        {
            case NdisNotificationType.NdisMediaConnect:
                @event = "Media Connected";
                break;
            case NdisNotificationType.NdisMediaDisconnect:
                @event = "Media Disconnected";
                break;
            case NdisNotificationType.NdisResetStart:
                @event = "Resetting";
                break;
            case NdisNotificationType.NdisResetEnd:
                @event = "Done resetting";
                break;
            case NdisNotificationType.NdisUnbind:
                @event = "Unbind";
                break;
            case NdisNotificationType.NdisBind:
                @event = "Bind";
                break;
            default:
                return;
        }

        if (this.InvokeRequired)
        {
            this.Invoke(new EventHandler(delegate
            {
                eventList.Items.Add(string.Format(
                                    "Adapter '{0}' {1}", e.AdapterName, @event));
            }));
        }
        else
        {
            eventList.Items.Add(string.Format(
                                "Adapter '{0}' {1}", e.AdapterName, @event));
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接