私はこのすべてにかなり新しいですが、私は質問を見て、私の質問に答えて何も見つけることができません。なぜNetworkChangeイベントが起動しないのですか
私は、ネットワーク設定が変更されたときにサーバーのいずれかに接続できるかどうかを確認する簡単なサービスを作成しています。
NetworkChangeクラス、NetworkAddressChangedおよびNetworkAvailabiltyChangedの2つのイベントを使用しています。
いずれかのサービスが起動すると、サーバーにpingを実行し、結果に応じてProxyEnableの設定が変更されます。
コード:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net.NetworkInformation;
using Microsoft.Win32;
namespace ProxyManager
{
public partial class ProxyManager : ServiceBase
{
static RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings",true);
static string currentProxy = rk.GetValue("ProxyEnable").ToString();
static string newProxy;
public ProxyManager()
{
InitializeComponent();
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
newProxy = "0";
}
protected override void OnStart(string[] args)
{
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
ProxySwitcher();
EventLog evt = new EventLog("ProxyManager");
string message = "Proxy Manager, Newtwork availabilty changed. Proxy switched to " + newProxy.ToString();
evt.Source = "Proxy Manager";
evt.WriteEntry(message,EventLogEntryType.Information);
}
void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
ProxySwitcher();
EventLog evt = new EventLog("ProxyManager");
string message = "Proxy Manager, Newtwork address changed. Proxy switched to " + newProxy.ToString();
evt.Source = "Proxy Manager";
evt.WriteEntry(message,EventLogEntryType.Information);
}
void ProxySwitcher()
{
if (currentProxy == "0")
{
newProxy = "1";
}
else
{
newProxy = "0";
}
try
{
Ping myPing = new Ping();
string host = "FILE SERVER";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success)
{
if (currentProxy == "0")
{
rk.SetValue("ProxyEnable", newProxy);
}
}
else
{
if (currentProxy == "1")
{
rk.SetValue("ProxyEnable", newProxy);
}
}
}
catch (PingException pingEx)
{
rk.SetValue("ProxyEnable", 0);
}
}
protected override void OnStop()
{
}
}
}
私の問題は、サービスがインストールされ、実行されている場合、イベントがいずれかのトリガされていないか、ピックアップされていないということです。関連するイベントが記録されず、プロキシが切り替えられていません。
私は実行可能なコンソールアプリケーションのイベントハンドラを除いたコードを試しましたが、これはネットワークの可用性に応じてうまくいきました。
私はWindows 7 x86を実行していますが、.NET 3.5でコーディングしています。
ご協力いただきありがとうございます。
私はまた、インターフェイスが上がったり下がったりすると、インターフェイスがダウンしたときにIPが0.0.0.0になり、インターフェイスが起動したときに適切なIPに復元するため、これらのイベントの両方が起きると言います。だから、両方のイベントをフックし、両方でProxySwitch()を実行することで、どこにも高速になることはありません。 –