Кабель Ethernet wpf отключенC#

Место общения программистов C#
Anonymous
Кабель Ethernet wpf отключен

Сообщение Anonymous »

Здравствуйте, я пытался найти код, позволяющий определить, отсоединен ли кабель Ethernet. Проблема в том, что большинство из них ориентированы на Интернет. У меня есть несколько устройств разных производителей, и я пытаюсь создать событие, когда питание перезагружается на устройство и/или сетевой коммутатор. По сути то же самое происходит при отключении кабеля от сетевого порта ПК. У меня есть код, но он не работает, и я пытаюсь понять, почему. Вот wpf.... Вот моя модель представления:

Код: Выделить всё

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
class MainViewModel : NotifyPropertyChangedBase
{
private readonly Dictionary _cache = new Dictionary();

private IReadOnlyList _interfaces;
public IReadOnlyList Interfaces
{
get { return _interfaces; }
private set { _UpdateField(ref _interfaces, value);  }
}

public MainViewModel()
{
NetworkChange.NetworkAvailabilityChanged += _OnNetworkAvailabilityChanged;
_RebuildInterfaceList();
}

private void _OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
foreach (NetworkInterfaceModel model in _interfaces)
{
if (model.PostEventStatus == PostEventStatus.Removed)
{
_cache.Remove(model.Name);
}
else
{
// Assume removed, until proven otherwise while rebuilding list
model.SetRemoved();
}
}

_RebuildInterfaceList();
}

private void _RebuildInterfaceList()
{
foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
NetworkInterfaceModel model;

if (!_cache.TryGetValue(networkInterface.Name, out model))
{
model = new NetworkInterfaceModel(networkInterface);
_cache.Add(model.Name, model);
}
else
{
model.Reset();
model.OperationalStatus = networkInterface.OperationalStatus;
}
}

Interfaces = Array.AsReadOnly(_cache.Values.OrderBy(m => m.Name).ToArray());
}
}
}
Вот моя модель сетевого интерфейса:

Код: Выделить всё

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
enum PostEventStatus
{
Added,
NoChange,
Changed,
Removed
}

class NetworkInterfaceModel : NotifyPropertyChangedBase
{
private string _name;
private OperationalStatus _status;
private PostEventStatus _postEventStatus = PostEventStatus.Added;

public NetworkInterfaceModel(NetworkInterface networkInterface)
{
_name = networkInterface.Name;
_status = networkInterface.OperationalStatus;
}

public string Name
{
get { return _name; }
set { _UpdateField(ref _name, value); }
}

public OperationalStatus OperationalStatus
{
get { return _status; }
set { _UpdateField(ref _status, value, _OnOperationalStatusChanged); }
}

public PostEventStatus PostEventStatus
{
get { return _postEventStatus; }
set { _UpdateField(ref _postEventStatus, value); }
}

public void Reset()
{
PostEventStatus = PostEventStatus.NoChange;
}

public void SetRemoved()
{
PostEventStatus = PostEventStatus.Removed;
}

private void _OnOperationalStatusChanged(OperationalStatus obj)
{
PostEventStatus = PostEventStatus.Changed;
}
}
}
А вот моя NotifyPropertyChangeBase:

Код: Выделить всё

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
class NotifyPropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected void _UpdateField(ref T field, T newValue,
Action onChangedCallback = null,
[CallerMemberName] string propertyName = null)
{
if (EqualityComparer.Default.Equals(field, newValue))
{
return;
}

T oldValue = field;

field = newValue;
onChangedCallback?.Invoke(oldValue);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Он ничего не сделает, если кабель отключен или подключен, пока я не перезапущу программу.

Подробнее здесь: https://stackoverflow.com/questions/788 ... sconnected

Вернуться в «C#»