English 中文(简体)
Windows 检测网络变化事件的服务
原标题:Windows Service to detect network change event

我需要在 C# 创建一个活动听众器, 让用户知道网络变化( 如新的 IP 地址) 。 我尝试过研究来寻找不同的方式来做到这一点, 但我在 C# 中没有看到如何具体做到这一点, 并且完成我需要完成的所有任务。 我正用这里提供的信息 < a href= > 建立一个听众器。 http://msdn. microsoft. com/ en- us/ library/zt39148a. aspx# Y570" rel = "no follow" > >http://msdn. microsoft. com/ en- us/library/zt39148a. aspx# Y570 < / a > 。 但这个对我来说也是行不通的。 Polling 可能是我最好的选择, 但如果有人能帮忙, 那会非常感激. I m op on XP and. NET 4.0 。

问题回答

您只需在服务范围内聆听网络变化事件:

public partial class Service1 : ServiceBase
{
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkAddressChanged);
    }

    protected override void OnStop()
    {
    }

    private void NetworkAddressChanged(object sender, EventArgs e)
    {
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface n in adapters)
        {
            EventLog.WriteEntry("NetworkMonitor",String.Format("{0} is {1}", n.Name, n.OperationalStatus),EventLogEntryType.Warning);
        }
    }

}

有关IP地址的信息可在网络接口中找到。

要在上述服务中获取 IP 地址信息, 需要这样的操作 :

IPInterfaceProperties adapterProperties = n.GetIPProperties();
IPAddressCollection addresses = adapterProperties.DhcpServerAddresses;
foreach (IPAddress address in addresses)
{
    //do something with address.ToString();
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签