页面部分
<Window x:Class="wpfTest.WifiWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
BorderThickness="0" AllowsTransparency="True" ResizeMode="CanResize" Background="Transparent"
BorderBrush="Transparent" WindowStartupLocation="CenterScreen" WindowStyle="None"
mc:Ignorable="d" Height="800" Width="1300" FontSize="28">
<Border Background="#FFFFFFFF" CornerRadius="6" Margin="10">
<Border.Effect>
<DropShadowEffect Opacity="1" Direction="0" BlurRadius="10" ShadowDepth="0"/>
</Border.Effect>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Margin="20,0,0,0">WLAN</TextBlock>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Margin="180,0,0,0" Foreground="Blue">WLAN连接需要几秒,请耐心等待......</TextBlock>
<Button Width="220" HorizontalAlignment="Right" Margin="170,0,260,0" Content="刷新" Click="Button_Click" />
<Button HorizontalAlignment="Right" Width="220" Margin="170,0,0,0"
Content="取消" Background="LightGray" Foreground="Black" Click="BtnClose_Click" />
</Grid>
<Grid Grid.Row="1">
<ListView x:Name="lv" Grid.Row="1"
ItemsSource="{Binding AccessPointList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" >
<ListView.View>
<GridView>
<GridViewColumn Header="名称" Width="860" DisplayMemberBinding="{Binding SSID}"/>
<GridViewColumn Header="是否需要密码" Width="200" DisplayMemberBinding="{Binding HasSSID}"/>
<GridViewColumn Header="操作">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DockPanel Height="60">
<Button x:Name="ConnectButton" Content="连接" Width="120" Style="{StaticResource GrayButton}" Background="#8e8e8e" Click="ConnectButton_OnClick"/>
</DockPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<TextBlock x:Name="NoWlanTextBlock" Grid.Row="1" Text="貌似没有无线网卡" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Red" Visibility="{Binding NoWlan}"/>
</Grid>
</Grid>
</Border>
</Window>
后台代码
/// <summary>
/// wifi管理 的交互逻辑
/// </summary>
public partial class WifiWin : Window
{
WifiViewModel vm { get; set; } = new WifiViewModel();
public WifiWin()
{
InitializeComponent();
this.DataContext = vm;
vm.ListAll();
}
/// <summary>
/// 连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ConnectButton_OnClick(object sender, RoutedEventArgs e)
{
if (!(sender is Button btn)) return;
if (!(btn.DataContext is Networks ap)) return;
vm.AP = ap;
vm.WifiProfiles();
if (vm.ProfilesList.FirstOrDefault(x => x == ap.SSID) != null)
{
vm.ConnectToWiFi();
}
else
{
var wifiPasswardInputWindow = new WifiSettingWin(ap.SSID);
wifiPasswardInputWindow.Owner = this;
wifiPasswardInputWindow.Comfirmed += WifiPasswardInputWindow_Comfirmed;
wifiPasswardInputWindow.ShowDialog();
}
}
/// <summary>
/// 连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void WifiPasswardInputWindow_Comfirmed(object sender, EventArgs e)
{
try
{
vm.IsShowLoading = Visibility.Visible;
if (sender is WifiSettingViewModel wifiInfoWindow)
{
vm.ConnectToWiFi(wifiInfoWindow.Password);
vm.ListAll();
}
}
catch (Exception ex)
{
Util.ShowMsg(ex.Message);
LogUtil.LogError(ex);
}
}
/// <summary>
/// 刷新
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
vm.ListAll();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
LogUtil.LogError(ex);
}
}
private void BtnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
public class WifiViewModel : CommunityToolkit.Mvvm.ComponentModel.ObservableObject
{
public WifiViewModel()
{
}
public ObservableCollection<Networks> AccessPointList { get; set; } = new ObservableCollection<Networks>();
Visibility _NoWlan;
public Visibility NoWlan { get => _NoWlan; set => SetProperty(ref _NoWlan, value); }
Networks _AP;
public Networks AP { get => _AP; set => SetProperty(ref _AP, value); }
List<string> _ProfilesList = new List<string>();
/// <summary>
/// 缓存wifi
/// </summary>
public List<string> ProfilesList { get => _ProfilesList; set => SetProperty(ref _ProfilesList, value); }
Visibility _IsShowLoading=Visibility.Collapsed;
public Visibility IsShowLoading { get => _IsShowLoading; set => SetProperty(ref _IsShowLoading, value); }
/// <summary>
/// 得到全部wifi列表
/// </summary>
public void ListAll()
{
try
{
string output = Util.RunCommand("wlan show networks");// 调用cmd命令,打开Wi-Fi连接列表
var profiles = ParseNetworks(output); // 解析Wi-Fi连接列表
WifiProfiles();
System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
{
AccessPointList.Clear();
if (profiles.Any())
{
foreach (var item in profiles)
{
if (!string.IsNullOrEmpty(item.SSID) && item.SSID != "\r")
{
if (ProfilesList.Contains(item.SSID))
{
item.HasSSID = "否";
}
else
{
item.HasSSID ="是";
}
AccessPointList.Add(item);
}
}
}
}));
NoWlan = AccessPointList.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
}
catch (Exception)
{
throw;
}
}
Networks[] ParseNetworks(string output)
{
// 使用正则表达式匹配每个网络块
Regex regex = new Regex(@"SSID \d+ : (.+?)\r?\n\s*Network type\s+: (.+?)\r?\n\s*身份验证\s+: (.+?)\r?\n\s*加密\s+: (.+?)\r?\n");
MatchCollection matches = regex.Matches(output);
// 提取匹配的网络信息
Networks[] networks = new Networks[matches.Count];
for (int i = 0; i < matches.Count; i++)
{
Match match = matches[i];
string ssid = match.Groups[1].Value;
string networkType = match.Groups[2].Value;
string authentication = match.Groups[3].Value;
string encryption = match.Groups[4].Value;
networks[i] = new Networks(ssid, networkType, authentication, encryption);
}
return networks;
}
void DisconnectWiFi()
{
Util.RunCommand("wlan disconnect");
}
/// <summary>
/// 有缓存的WiFi连接
/// </summary>
public void ConnectToWiFi()
{
DisconnectWiFi();
string conn = $"wlan connect name = {AP.SSID} ssid = {AP.SSID}";
Util.RunCommand(conn);
Thread.Sleep(3000);
string connectionStatus = GetWiFiConnectionStatus();
Util.ShowMsg("WiFi连接状态: " + connectionStatus);
if (connectionStatus != "已连接")
{
DeleteWiFiPassword(AP.SSID);
ListAll();
}
IsShowLoading = Visibility.Collapsed;
}
/// <summary>
/// 无缓存的WiFi连接
/// </summary>
/// <param name="password"></param>
public void ConnectToWiFi(string password)
{
DisconnectWiFi();
string command = $"wlan set profileparameter name = {AP.SSID} SSIDname={AP.SSID} keyMaterial = {password}";
Util.RunCommand(command);
string conn = $"wlan connect name = {AP.SSID} ssid = {AP.SSID}";
Util.RunCommand(conn);
Thread.Sleep(3000);
string connectionStatus = GetWiFiConnectionStatus();
Util.ShowMsg("WiFi连接状态: " + connectionStatus);
if (connectionStatus != "已连接")
{
DeleteWiFiPassword(AP.SSID);
ListAll();
}
IsShowLoading = Visibility.Collapsed;
}
/// <summary>
/// 查找所有缓存列表
/// </summary>
public void WifiProfiles()
{
try
{
string output = Util.RunCommand("wlan show profiles");
// 解析Wi-Fi连接列表
string[] profiles = ParseProfiles(output);
if (profiles.Length > 0) { ProfilesList = profiles.ToList(); }
}
catch (Exception ex)
{
LogUtil.LogError(ex);
}
}
string[] ParseProfiles(string output)
{
string patternUser = @"所有用户配置文件 : (.+?)\r\n";// 使用正则表达式提取用户配置文件
MatchCollection userConfigs = Regex.Matches(output, patternUser);
// 提取匹配的连接名称
string[] profiles = new string[userConfigs.Count];
Console.WriteLine("用户配置文件:");
for (int i = 0; i < userConfigs.Count; i++)
{
profiles[i] = userConfigs[i].Groups[1].Value;
}
return profiles;
}
/// <summary>
/// 获取当前wifi的状态
/// </summary>
/// <returns></returns>
public string GetWiFiConnectionStatus()
{
string command = "wlan show interfaces";
string output = Util.RunCommand(command);
// 解析输出以获取连接状态
string[] lines = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (line.Contains("状态"))
{
int startIndex = line.IndexOf(":") + 1;
string status = line.Substring(startIndex).Trim();
return status;
}
}
return "未知";
}
public void DeleteWiFiPassword(string profileName)
{
string command = $"wlan delete profile name=\"{profileName}\"";
Util.RunCommand(command);
}
}
public class Util
{
/// <summary>
/// 直接跑命令行
/// </summary>
/// <param name="command">命令行</param>
/// <returns></returns>
public static string RunCommand(string command)
{
string result=null;
try
{
Process process = new Process();
process.StartInfo.FileName = "netsh";
process.StartInfo.Arguments = $"{command}"; // 替换为实际的命令参数
process.StartInfo.UseShellExecute = false; //此处必须为false否则引发异常
process.StartInfo.RedirectStandardInput = true; //标准输入
process.StartInfo.RedirectStandardOutput = true; //标准输出
process.StartInfo.CreateNoWindow = true; //不显示命令行窗口界面
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close();
}
catch (Exception ex)
{
LogUtil.LogError(ex);
}
return result;
}
/// <summary>
/// 直接跑命令行
/// </summary>
/// <param name="command">命令行</param>
/// <returns></returns>
public static string RunCommand(string filename,string command)
{
string result=null;
try
{
Process process = new Process();
process.StartInfo.FileName = filename;
process.StartInfo.Arguments = $"{command}"; // 替换为实际的命令参数
process.StartInfo.UseShellExecute = false; //此处必须为false否则引发异常
process.StartInfo.RedirectStandardInput = true; //标准输入
process.StartInfo.RedirectStandardOutput = true; //标准输出
process.StartInfo.CreateNoWindow = true; //不显示命令行窗口界面
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close();
}
catch (Exception ex)
{
LogUtil.LogError(ex);
}
return result;
}
}