Compare commits

..

5 Commits

Author SHA1 Message Date
2dust
71645cbbce Add NetBridge process hijacking feature for windows
https://github.com/2dust/NetBridge
https://github.com/InterceptSuite/ProxyBridge
2026-06-09 15:37:39 +08:00
2dust
b1a400b393 binConfigs only deletes test files periodically 2026-06-08 14:22:11 +08:00
2dust
879c736924 Update Utils.cs
5fed566a32
2026-06-07 15:49:31 +08:00
sparklelcm333
8147b39723 fix: 在窗口初始化前设置保存的尺寸,消除启动时偏右下偏移 (#9498)
* fix: 在窗口初始化前设置保存的尺寸,消除启动时偏右下偏移

WindowStartupLocation="CenterScreen"(来自 XAML)能正确包含 chrome 居中窗口,
但只能使用生效时的 Width/Height。旧代码在 OnLoaded 中设置保存的尺寸为时已晚
(CenterScreen 已应用),随后又用不含 chrome 的手工计算覆盖 Position,
导致窗口每次启动偏右下。

修复方式:在 Initialized 事件中设置保存的 Width/Height。
Avalonia 中 Initialized 在 Show() 过程中触发,早于 WindowStartupLocation 生效,
因此 CenterScreen 能用正确的保存尺寸居中。

同时移除 OnLoaded 中重复的 Width/Height 设置(Initialized 中已设置)。

* Update WindowBase.cs

---------

Co-authored-by: 2dust <31833384+2dust@users.noreply.github.com>
2026-06-07 14:59:50 +08:00
2dust
5fed566a32 Add ReplaceLineBreaks extension and Fix bug
https://github.com/2dust/v2rayN/issues/9497
2026-06-07 14:49:39 +08:00
27 changed files with 695 additions and 22 deletions

3
.gitmodules vendored
View File

@@ -1,3 +1,6 @@
[submodule "v2rayN/GlobalHotKeys"]
path = v2rayN/GlobalHotKeys
url = https://github.com/2dust/GlobalHotKeys
[submodule "v2rayN/NetBridge"]
path = v2rayN/NetBridge
url = https://github.com/2dust/NetBridge

View File

@@ -118,4 +118,20 @@ public static class Extension
destination.Add(item);
}
}
/// <summary>
/// Replace all cross-platform newline characters with the specified string
/// </summary>
public static string ReplaceLineBreaks(this string input, string replacement)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
// You must replace \r\n first, and then replace the single characters \r and \n.
return input.Replace("\r\n", replacement)
.Replace("\r", replacement)
.Replace("\n", replacement);
}
}

View File

@@ -202,7 +202,7 @@ public static class FileUtils
}
}
public static void DeleteExpiredFiles(string sourceDir, DateTime dtLine)
public static void DeleteExpiredFiles(string sourceDir, DateTime dtLine, string? contains = null)
{
try
{
@@ -214,6 +214,10 @@ public static class FileUtils
{
continue;
}
if (contains.IsNotEmpty() && !file.Name.Contains(contains))
{
continue;
}
file.Delete();
}
}

View File

@@ -51,7 +51,7 @@ public class Utils
try
{
str = str.Replace(Environment.NewLine, string.Empty);
str = str.ReplaceLineBreaks(string.Empty);
return new List<string>(str.Split(',', StringSplitOptions.RemoveEmptyEntries));
}
catch (Exception ex)
@@ -114,9 +114,7 @@ public class Utils
}
plainText = plainText.Trim()
.Replace(Environment.NewLine, "")
.Replace("\n", "")
.Replace("\r", "")
.ReplaceLineBreaks("")
.Replace('_', '/')
.Replace('-', '+')
.Replace(" ", "");
@@ -321,7 +319,9 @@ public class Utils
return text;
}
return text.Replace("", ",").Replace(Environment.NewLine, ",");
return text.Replace("", ",")
.Replace(" ", "")
.ReplaceLineBreaks(",");
}
public static List<string> GetEnumNames<TEnum>() where TEnum : Enum

View File

@@ -161,6 +161,10 @@ public static class ConfigHandler
config.SystemProxyItem ??= new();
config.WebDavItem ??= new();
config.CheckUpdateItem ??= new();
config.NetBridgeItem ??= new()
{
RuleProcess = string.Empty
};
config.Fragment4RayItem ??= new()
{
Packets = "tlshello",

View File

@@ -0,0 +1,222 @@
using NetBridgeLib.Services;
namespace ServiceLib.Manager;
public sealed class NetBridgeManager
{
private static readonly Lazy<NetBridgeManager> _instance = new(() => new());
public static NetBridgeManager Instance => _instance.Value;
private readonly Config _config = AppManager.Instance.Config;
private NetBridgeService? _netBridgeService;
private bool _isProxyRunning;
private bool _isInitialized;
private List<NetBridgeRuleConfig> _ruleConfigs = [];
private Func<bool, string, Task>? _updateFunc;
private uint _proxyConfigId;
public async Task Init(Func<bool, string, Task>? updateFunc = null)
{
if (_isInitialized)
{
return;
}
_updateFunc = updateFunc;
try
{
_netBridgeService = new NetBridgeService();
_netBridgeService.LogReceived += msg =>
{
var message = $"NetBridge Log: {msg}";
_ = _updateFunc?.Invoke(false, message);
};
_netBridgeService.ConnectionReceived += (processName, pid, destIp, destPort, proxyInfo) =>
{
var message = $"NetBridge Connection: {processName} (PID: {pid}) -> {destIp}:{destPort} -> {proxyInfo}";
_ = _updateFunc?.Invoke(false, message);
};
_ruleConfigs = BuildRuleConfigs(_config.NetBridgeItem?.RuleProcess);
_isInitialized = true;
}
catch (Exception ex)
{
var error = $"Failed to initialize NetBridgeService: {ex.Message}";
await _updateFunc?.Invoke(true, error);
}
}
public async Task<bool> Start()
{
if (_isProxyRunning)
{
return true;
}
try
{
if (_netBridgeService == null)
{
return false;
}
var started = _netBridgeService.Start();
if (!started)
{
return false;
}
_isProxyRunning = true;
}
catch (Exception ex)
{
var error = $"Failed to start NetBridgeService: {ex.Message}";
await _updateFunc?.Invoke(true, error);
return false;
}
return true;
}
public async Task<bool> Stop()
{
if (!_isProxyRunning)
{
return true;
}
try
{
if (_netBridgeService == null)
{
return false;
}
var stopped = _netBridgeService.Stop();
if (!stopped)
{
return false;
}
_isProxyRunning = false;
}
catch (Exception ex)
{
var error = $"Failed to stop NetBridgeService: {ex.Message}";
await _updateFunc?.Invoke(true, error);
return false;
}
return true;
}
public async Task<bool> UpdateRoutes(string? ruleProcess)
{
var newRuleConfigs = BuildRuleConfigs(ruleProcess);
_ruleConfigs = newRuleConfigs;
if (!_isProxyRunning)
{
return true;
}
return await ApplyRoutesInternal();
}
public async Task<bool> UpdateProxyConfig(string proxyHost, int proxyPort)
{
try
{
if (_netBridgeService == null)
{
return false;
}
var proxyType = "SOCKS5";
var username = "";
var password = "";
if (_proxyConfigId > 0)
{
var edited = _netBridgeService.EditProxyConfig(_proxyConfigId, proxyType, proxyHost, (ushort)proxyPort, username, password);
if (!edited)
{
return false;
}
}
else
{
_proxyConfigId = _netBridgeService.AddProxyConfig(proxyType, proxyHost, (ushort)proxyPort, username, password);
if (_proxyConfigId == 0)
{
return false;
}
}
return await Task.FromResult(true);
}
catch (Exception ex)
{
var error = $"Failed to update proxy config: {ex.Message}";
await _updateFunc?.Invoke(true, error);
return false;
}
}
private async Task<bool> ApplyRoutesInternal()
{
if (_netBridgeService == null)
{
return false;
}
List<NetBridgeRuleConfig> rules;
rules = _ruleConfigs.Select(JsonUtils.DeepCopy).ToList();
foreach (var rule in rules.Where(x => x.RuleId > 0))
{
try
{
_ = _netBridgeService.DeleteRule(rule.RuleId);
}
catch
{
// ignored
}
}
for (var i = 0; i < rules.Count; i++)
{
var rule = rules[i];
var newRuleId = _netBridgeService.AddRule(rule.ProcessName, rule.TargetHosts, rule.TargetPorts, rule.Protocol, rule.Action, rule.ProxyConfigId);
if (newRuleId == 0)
{
return false;
}
rules[i].RuleId = newRuleId;
}
_ruleConfigs = rules;
return await Task.FromResult(true);
}
private static List<NetBridgeRuleConfig> BuildRuleConfigs(string? ruleProcess)
{
var processNames = Utils.String2List(Utils.Convert2Comma(ruleProcess));
return processNames.Select(processName => new NetBridgeRuleConfig
{
ProcessName = processName,
TargetHosts = "*",
TargetPorts = "*",
Protocol = "BOTH",
Action = "PROXY",
ProxyConfigId = 0
}).ToList();
}
}

View File

@@ -56,7 +56,7 @@ public class TaskManager
{
//Logging.SaveLog("Execute delete expired files");
FileUtils.DeleteExpiredFiles(Utils.GetBinConfigPath(), DateTime.Now.AddHours(-1));
FileUtils.DeleteExpiredFiles(Utils.GetBinConfigPath(), DateTime.Now.AddHours(-1), "Test");
FileUtils.DeleteExpiredFiles(Utils.GetLogPath(), DateTime.Now.AddMonths(-1));
FileUtils.DeleteExpiredFiles(Utils.GetTempPath(), DateTime.Now.AddMonths(-1));

View File

@@ -29,6 +29,7 @@ public class Config
public SystemProxyItem SystemProxyItem { get; set; }
public WebDavItem WebDavItem { get; set; }
public CheckUpdateItem CheckUpdateItem { get; set; }
public NetBridgeItem NetBridgeItem { get; set; }
public Fragment4RayItem? Fragment4RayItem { get; set; }
public List<InItem> Inbound { get; set; }
public List<KeyEventItem> GlobalHotkeys { get; set; }

View File

@@ -277,3 +277,9 @@ public class SimpleDNSItem
public string? Hosts { get; set; }
public string? DirectExpectedIPs { get; set; }
}
[Serializable]
public class NetBridgeItem
{
public string? RuleProcess { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace ServiceLib.Models.Dto;
public sealed class NetBridgeRuleConfig
{
public uint RuleId { get; set; }
public string ProcessName { get; set; }
public string TargetHosts { get; set; }
public string TargetPorts { get; set; }
public string Protocol { get; set; }
public string Action { get; set; }
public uint ProxyConfigId { get; set; }
}

View File

@@ -1320,6 +1320,15 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 Process traffic hijacking (experimental) 的本地化字符串。
/// </summary>
public static string menuNetBridge {
get {
return ResourceManager.GetString("menuNetBridge", resourceCulture);
}
}
/// <summary>
/// 查找类似 New Update 的本地化字符串。
/// </summary>
@@ -2301,6 +2310,15 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 The process names that need to be proxied; separate multiple processes with commas. Processes not in the list will also be hijacked, but will connect directly. 的本地化字符串。
/// </summary>
public static string NetBridgeRuleTips {
get {
return ResourceManager.GetString("NetBridgeRuleTips", resourceCulture);
}
}
/// <summary>
/// 查找类似 Non-VMess or SS protocol 的本地化字符串。
/// </summary>
@@ -3051,6 +3069,15 @@ namespace ServiceLib.Resx {
}
}
/// <summary>
/// 查找类似 Enables process traffic hijacking (experimental), similar to Proxifer; can coexist with system proxy; conflicts with TUN mode, please do not enable them simultaneously; 的本地化字符串。
/// </summary>
public static string TbEnableNetBridge {
get {
return ResourceManager.GetString("TbEnableNetBridge", resourceCulture);
}
}
/// <summary>
/// 查找类似 Enable Tun 的本地化字符串。
/// </summary>

View File

@@ -1770,4 +1770,13 @@ The "Get Certificate" action may fail if a self-signed certificate is used or if
<data name="TbEnableFinalFragmentTip" xml:space="preserve">
<value>Split the tail of packets into smaller fragments. This may affect throughput and latency.</value>
</data>
</root>
<data name="TbEnableNetBridge" xml:space="preserve">
<value>Enables process traffic hijacking (experimental), similar to Proxifer; can coexist with system proxy; conflicts with TUN mode, please do not enable them simultaneously;</value>
</data>
<data name="NetBridgeRuleTips" xml:space="preserve">
<value>The process names that need to be proxied; separate multiple processes with commas. Processes not in the list will also be hijacked, but will connect directly.</value>
</data>
<data name="menuNetBridge" xml:space="preserve">
<value>Process traffic hijacking (experimental)</value>
</data>
</root>

View File

@@ -1767,4 +1767,13 @@
<data name="TbEnableFinalFragmentTip" xml:space="preserve">
<value>将数据包末端拆分为更小片段发送,可能影响吞吐与延迟。</value>
</data>
<data name="TbEnableNetBridge" xml:space="preserve">
<value>启用进程流量劫持(实验性),类似 Proxifer 功能;可以和系统代理并存;和 TUN 模式冲突,请不要同时开启;</value>
</data>
<data name="NetBridgeRuleTips" xml:space="preserve">
<value>需要代理的进程名,多个进程请用逗号分隔;不在列表中的进程也会被劫持,但是会直连</value>
</data>
<data name="menuNetBridge" xml:space="preserve">
<value>进程流量劫持(实验性)</value>
</data>
</root>

View File

@@ -1767,4 +1767,13 @@
<data name="TbEnableFinalFragmentTip" xml:space="preserve">
<value>將封包末端拆分為更小的片段進行傳送,可能會影響吞吐量與延遲</value>
</data>
</root>
<data name="TbEnableNetBridge" xml:space="preserve">
<value>啟用進程流量劫持(實驗性),類似 Proxifer 功能;可以和系統代理並存;和 TUN 模式衝突,請不要同時開啟;</value>
</data>
<data name="NetBridgeRuleTips" xml:space="preserve">
<value>需要代理程式的進程名,多個進程請用逗號分隔;不在清單中的進程也會被劫持,但是會直連</value>
</data>
<data name="menuNetBridge" xml:space="preserve">
<value>進程流量劫持(實驗性)</value>
</data>
</root>

View File

@@ -87,6 +87,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NetBridge\src\NetBridgeLib\NetBridgeLib.csproj" />
<ProjectReference Include="..\ServiceLib.UdpTest\ServiceLib.UdpTest.csproj" />
</ItemGroup>

View File

@@ -0,0 +1,100 @@
namespace ServiceLib.ViewModels;
public class NetBridgeViewModel : MyReactiveObject
{
[Reactive]
public bool EnableNetBridge { get; set; }
[Reactive]
public string RuleProcess { get; set; }
public ReactiveCommand<Unit, Unit> SaveRulesCmd { get; }
public NetBridgeViewModel(Func<EViewAction, object?, Task<bool>>? updateView)
{
_config = AppManager.Instance.Config;
_updateView = updateView;
SaveRulesCmd = ReactiveCommand.CreateFromTask(async () =>
{
await SaveRulesAsync();
});
this.WhenAnyValue(x => x.EnableNetBridge)
.Skip(1)
.Subscribe(async enabled =>
{
await ToggleNetBridgeAsync(enabled);
});
_ = Init();
}
private async Task Init()
{
_config.NetBridgeItem ??= new()
{
RuleProcess = string.Empty
};
EnableNetBridge = false;
RuleProcess = _config.NetBridgeItem.RuleProcess;
if (RuleProcess.IsNullOrEmpty())
{
RuleProcess = "Chrome.exe";
}
await Task.CompletedTask;
}
private async Task ToggleNetBridgeAsync(bool enabled)
{
await NetBridgeManager.Instance.Init(UpdateViewHandler);
if (enabled)
{
var succeed = await NetBridgeManager.Instance.Start();
if (succeed)
{
await NetBridgeManager.Instance.UpdateProxyConfig(Global.Loopback, AppManager.Instance.GetLocalPort(EInboundProtocol.socks));
await NetBridgeManager.Instance.UpdateRoutes(RuleProcess);
}
NoticeManager.Instance.Enqueue(succeed ? ResUI.OperationSuccess : ResUI.OperationFailed);
}
else
{
var succeed = await NetBridgeManager.Instance.Stop();
NoticeManager.Instance.Enqueue(succeed ? ResUI.OperationSuccess : ResUI.OperationFailed);
}
}
/// </summary>
private async Task SaveRulesAsync()
{
_config.NetBridgeItem ??= new();
var normalizedRuleProcess = RuleProcess;
_config.NetBridgeItem.RuleProcess = normalizedRuleProcess;
RuleProcess = normalizedRuleProcess;
if (await ConfigHandler.SaveConfig(_config) != 0)
{
NoticeManager.Instance.Enqueue(ResUI.OperationFailed);
return;
}
await NetBridgeManager.Instance.Init(UpdateViewHandler);
if (EnableNetBridge)
{
var routesUpdated = await NetBridgeManager.Instance.UpdateRoutes(normalizedRuleProcess);
NoticeManager.Instance.Enqueue(routesUpdated ? ResUI.OperationSuccess : ResUI.OperationFailed);
}
}
private async Task<bool> UpdateViewHandler(bool isError, string msg)
{
NoticeManager.Instance.SendMessageEx(msg);
return await Task.FromResult(true);
}
}

View File

@@ -4,6 +4,7 @@ public class WindowBase<TViewModel> : ReactiveWindow<TViewModel> where TViewMode
{
public WindowBase()
{
Initialized += OnWindowInitialized;
Loaded += OnLoaded;
}
@@ -12,30 +13,33 @@ public class WindowBase<TViewModel> : ReactiveWindow<TViewModel> where TViewMode
throw new NotImplementedException();
}
protected virtual void OnLoaded(object? sender, RoutedEventArgs e)
private void OnWindowInitialized(object? sender, EventArgs e)
{
try
{
var sizeItem = ConfigHandler.GetWindowSizeItem(AppManager.Instance.Config, GetType().Name);
if (sizeItem == null)
if (sizeItem is null)
{
return;
}
Width = sizeItem.Width;
Height = sizeItem.Height;
if (sizeItem.Width > 0 && !Width.Equals(sizeItem.Width))
{
Width = sizeItem.Width;
}
var workingArea = (Screens.ScreenFromWindow(this) ?? Screens.Primary).WorkingArea;
var scaling = (Utils.IsMacOS() ? null : VisualRoot?.RenderScaling) ?? 1.0;
var x = workingArea.X + ((workingArea.Width - (Width * scaling)) / 2);
var y = workingArea.Y + ((workingArea.Height - (Height * scaling)) / 2);
Position = new PixelPoint((int)x, (int)y);
if (sizeItem.Height > 0 && !Height.Equals(sizeItem.Height))
{
Height = sizeItem.Height;
}
}
catch { }
}
protected virtual void OnLoaded(object? sender, RoutedEventArgs e)
{
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);

View File

@@ -89,6 +89,7 @@
</MenuItem>
<MenuItem x:Name="menuBackupAndRestore" Header="{x:Static resx:ResUI.menuBackupAndRestore}" />
<MenuItem x:Name="menuOpenTheFileLocation" Header="{x:Static resx:ResUI.menuOpenTheFileLocation}" />
<MenuItem x:Name="menuNetBridge" Header="{x:Static resx:ResUI.menuNetBridge}" />
</MenuItem>
<MenuItem x:Name="menuHelp" Header="{x:Static resx:ResUI.menuHelp}">

View File

@@ -12,6 +12,7 @@ public partial class MainWindow : WindowBase<MainWindowViewModel>
private readonly WindowNotificationManager? _manager;
private CheckUpdateView? _checkUpdateView;
private BackupAndRestoreView? _backupAndRestoreView;
private NetBridgeView? _netBridgeView;
private bool _blCloseByUser = false;
public MainWindow()
@@ -28,6 +29,7 @@ public partial class MainWindow : WindowBase<MainWindowViewModel>
btnNewUpdate.Click += MenuCheckUpdate_Click;
menuBackupAndRestore.Click += MenuBackupAndRestore_Click;
menuClose.Click += MenuClose_Click;
menuNetBridge.Click += MenuNetBridge_Click;
ViewModel = new MainWindowViewModel(UpdateViewHandler);
@@ -165,6 +167,7 @@ public partial class MainWindow : WindowBase<MainWindowViewModel>
{
Title = $"{Utils.GetVersion()}";
menuAddServerViaScan.IsVisible = false;
menuNetBridge.IsVisible = false;
}
if (_config.UiItem.AutoHideStartup && Utils.IsWindows())
@@ -379,6 +382,19 @@ public partial class MainWindow : WindowBase<MainWindowViewModel>
DialogHost.Show(_backupAndRestoreView);
}
private void MenuNetBridge_Click(object? sender, RoutedEventArgs e)
{
if (Utils.IsAdministrator())
{
_netBridgeView ??= new NetBridgeView();
DialogHost.Show(_netBridgeView);
}
else
{
NoticeManager.Instance.SendMessageAndEnqueue(ResUI.RunAsAdmin);
}
}
private async void MenuClose_Click(object? sender, RoutedEventArgs e)
{
if (await UI.ShowYesNo(this, ResUI.menuExitTips) != ButtonResult.Yes)

View File

@@ -0,0 +1,75 @@
<UserControl
x:Class="v2rayN.Desktop.Views.NetBridgeView"
xmlns="https://github.com/avaloniaui"
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"
xmlns:resx="clr-namespace:ServiceLib.Resx;assembly=ServiceLib"
xmlns:vms="clr-namespace:ServiceLib.ViewModels;assembly=ServiceLib"
d:DesignHeight="400"
d:DesignWidth="600"
x:DataType="vms:NetBridgeViewModel"
mc:Ignorable="d">
<Border
Margin="{StaticResource Margin8}"
VerticalAlignment="Center"
Theme="{DynamicResource CardBorder}">
<DockPanel Margin="{StaticResource Margin8}">
<StackPanel
Margin="{StaticResource Margin8}"
DockPanel.Dock="Top"
Orientation="Horizontal">
<ToggleSwitch
x:Name="togEnableNetBridge"
Margin="{StaticResource Margin8}"
HorizontalAlignment="Left" />
<TextBlock
Width="500"
Margin="{StaticResource Margin8}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.TbEnableNetBridge}"
TextWrapping="Wrap" />
</StackPanel>
<DockPanel>
<StackPanel
Margin="{StaticResource Margin8}"
DockPanel.Dock="Top"
Orientation="Horizontal">
<TextBlock
Width="500"
Margin="{StaticResource Margin8}"
VerticalAlignment="Center"
Text="{x:Static resx:ResUI.NetBridgeRuleTips}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel
Margin="{StaticResource Margin8}"
HorizontalAlignment="Right"
DockPanel.Dock="Bottom"
Orientation="Horizontal">
<Button
x:Name="btnSave"
Width="100"
Content="{x:Static resx:ResUI.TbConfirm}"
IsDefault="True" />
</StackPanel>
<TextBox
x:Name="txtRuleProcess"
Margin="{StaticResource Margin8}"
VerticalAlignment="Stretch"
AcceptsReturn="True"
BorderThickness="1"
Classes="TextArea"
TextWrapping="Wrap" />
</DockPanel>
</DockPanel>
</Border>
</UserControl>

View File

@@ -0,0 +1,25 @@
namespace v2rayN.Desktop.Views;
public partial class NetBridgeView : ReactiveUserControl<NetBridgeViewModel>
{
public NetBridgeView()
{
InitializeComponent();
ViewModel = new NetBridgeViewModel(UpdateViewHandler);
this.WhenActivated(disposables =>
{
this.BindCommand(ViewModel, vm => vm.SaveRulesCmd, v => v.btnSave).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.EnableNetBridge, v => v.togEnableNetBridge.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.RuleProcess, v => v.txtRuleProcess.Text).DisposeWith(disposables);
});
}
private async Task<bool> UpdateViewHandler(EViewAction action, object? obj)
{
return await Task.FromResult(true);
}
}

View File

@@ -1,7 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 18
VisualStudioVersion = 18.5.11709.299 stable
VisualStudioVersion = 18.5.11709.299
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "v2rayN", "v2rayN\v2rayN.csproj", "{6DE127CA-1763-4236-B297-D2EF9CB2EC9B}"
EndProject
@@ -36,6 +35,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServiceLib.Tests", "Service
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServiceLib.UdpTest", "ServiceLib.UdpTest\ServiceLib.UdpTest.csproj", "{CE9D9298-0289-4718-2522-B236489F2912}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetBridgeLib", "NetBridge\src\NetBridgeLib\NetBridgeLib.csproj", "{4AF81950-DD4E-A636-6BD5-B4A7839D87B0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -70,6 +71,10 @@ Global
{CE9D9298-0289-4718-2522-B236489F2912}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CE9D9298-0289-4718-2522-B236489F2912}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CE9D9298-0289-4718-2522-B236489F2912}.Release|Any CPU.Build.0 = Release|Any CPU
{4AF81950-DD4E-A636-6BD5-B4A7839D87B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4AF81950-DD4E-A636-6BD5-B4A7839D87B0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4AF81950-DD4E-A636-6BD5-B4A7839D87B0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4AF81950-DD4E-A636-6BD5-B4A7839D87B0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -16,6 +16,7 @@
</Folder>
<Project Path="AmazTool/AmazTool.csproj" />
<Project Path="GlobalHotKeys/src/GlobalHotKeys/GlobalHotKeys.csproj" />
<Project Path="NetBridge/src/NetBridgeLib/NetBridgeLib.csproj" />
<Project Path="ServiceLib.Tests/ServiceLib.Tests.csproj" />
<Project Path="ServiceLib.UdpTest/ServiceLib.UdpTest.csproj" Id="77930428-4dc4-4130-9031-6b9e714f5d20" />
<Project Path="ServiceLib/ServiceLib.csproj" />

View File

@@ -233,6 +233,10 @@
x:Name="menuOpenTheFileLocation"
Height="{StaticResource MenuItemHeight}"
Header="{x:Static resx:ResUI.menuOpenTheFileLocation}" />
<MenuItem
x:Name="menuNetBridge"
Height="{StaticResource MenuItemHeight}"
Header="{x:Static resx:ResUI.menuNetBridge}" />
</MenuItem>
</Menu>
<Separator />

View File

@@ -10,6 +10,7 @@ public partial class MainWindow
private static Config _config;
private CheckUpdateView? _checkUpdateView;
private BackupAndRestoreView? _backupAndRestoreView;
private NetBridgeView? _netBridgeView;
public MainWindow()
{
@@ -27,6 +28,7 @@ public partial class MainWindow
menuCheckUpdate.Click += MenuCheckUpdate_Click;
btnNewUpdate.Click += MenuCheckUpdate_Click;
menuBackupAndRestore.Click += MenuBackupAndRestore_Click;
menuNetBridge.Click += MenuNetBridge_Click;
ViewModel = new MainWindowViewModel(UpdateViewHandler);
@@ -376,6 +378,19 @@ public partial class MainWindow
DialogHost.Show(_backupAndRestoreView, "RootDialog");
}
private void MenuNetBridge_Click(object sender, RoutedEventArgs e)
{
if (Utils.IsAdministrator())
{
_netBridgeView ??= new NetBridgeView();
DialogHost.Show(_netBridgeView, "RootDialog");
}
else
{
NoticeManager.Instance.SendMessageAndEnqueue(ResUI.RunAsAdmin);
}
}
#endregion Event
#region UI

View File

@@ -0,0 +1,79 @@
<reactiveui:ReactiveUserControl
x:Class="v2rayN.Views.NetBridgeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:v2rayN.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:reactiveui="http://reactiveui.net"
xmlns:resx="clr-namespace:ServiceLib.Resx;assembly=ServiceLib"
xmlns:vms="clr-namespace:ServiceLib.ViewModels;assembly=ServiceLib"
Height="400"
d:DesignHeight="400"
d:DesignWidth="600"
x:TypeArguments="vms:NetBridgeViewModel"
Style="{StaticResource ViewGlobal}"
mc:Ignorable="d">
<DockPanel Margin="{StaticResource Margin8}">
<StackPanel
Margin="{StaticResource Margin8}"
DockPanel.Dock="Top"
Orientation="Horizontal">
<ToggleButton
x:Name="togEnableNetBridge"
Margin="{StaticResource Margin8}"
HorizontalAlignment="Left" />
<TextBlock
Width="500"
Margin="{StaticResource Margin8}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.TbEnableNetBridge}"
TextWrapping="Wrap" />
</StackPanel>
<DockPanel>
<StackPanel
Margin="{StaticResource Margin8}"
DockPanel.Dock="Top"
Orientation="Horizontal">
<TextBlock
Width="500"
Margin="{StaticResource Margin8}"
VerticalAlignment="Center"
Style="{StaticResource ToolbarTextBlock}"
Text="{x:Static resx:ResUI.NetBridgeRuleTips}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel
Margin="{StaticResource Margin8}"
HorizontalAlignment="Right"
DockPanel.Dock="Bottom"
Orientation="Horizontal">
<Button
x:Name="btnSave"
Width="100"
Content="{x:Static resx:ResUI.TbConfirm}"
IsDefault="True"
Style="{StaticResource DefButton}" />
</StackPanel>
<TextBox
x:Name="txtRuleProcess"
Margin="{StaticResource Margin8}"
VerticalAlignment="Stretch"
AcceptsReturn="True"
BorderThickness="1"
Style="{StaticResource DefTextBox}"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto" />
</DockPanel>
</DockPanel>
</reactiveui:ReactiveUserControl>

View File

@@ -0,0 +1,25 @@
namespace v2rayN.Views;
public partial class NetBridgeView
{
public NetBridgeView()
{
InitializeComponent();
ViewModel = new NetBridgeViewModel(UpdateViewHandler);
this.WhenActivated(disposables =>
{
this.BindCommand(ViewModel, vm => vm.SaveRulesCmd, v => v.btnSave).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.EnableNetBridge, v => v.togEnableNetBridge.IsChecked).DisposeWith(disposables);
this.Bind(ViewModel, vm => vm.RuleProcess, v => v.txtRuleProcess.Text).DisposeWith(disposables);
});
}
private async Task<bool> UpdateViewHandler(EViewAction action, object? obj)
{
return await Task.FromResult(true);
}
}