Compare commits

...
72 Commits
Author SHA1 Message Date
辉鸭蛋 58d79d5955 Revert "测试代码"
This reverts commit d1fcb9c21d.
2025-01-19 19:35:16 +08:00
辉鸭蛋 d1fcb9c21d 测试代码 2025-01-19 19:32:15 +08:00
辉鸭蛋 0314644892 10.39.5 2025-01-19 14:52:56 +08:00
辉鸭蛋 978ff67135 change mixer 2025-01-19 14:30:44 +08:00
辉鸭蛋 b93a651be6 10.39.4 2025-01-17 00:58:05 +08:00
辉鸭蛋 153e76f50f DxDiag 2025-01-15 00:32:09 +08:00
辉鸭蛋 a5824baa51 ++ 2025-01-14 01:49:48 +08:00
辉鸭蛋 8aded2bd48 + 2025-01-14 00:28:42 +08:00
辉鸭蛋 d57564c74c + 2025-01-13 23:46:00 +08:00
辉鸭蛋 ee36818314 + 2025-01-12 19:13:30 +08:00
辉鸭蛋 b6e6fc1269 shift 5 2025-01-12 18:32:27 +08:00
辉鸭蛋 7e302c3bd8 done 2025-01-12 17:51:56 +08:00
辉鸭蛋 43cedcf8a7 up+ 2025-01-12 17:39:17 +08:00
辉鸭蛋 a532f8ab29 uploaded 2025-01-12 17:06:06 +08:00
辉鸭蛋 39c043bf3f easy upload 2025-01-12 16:20:58 +08:00
辉鸭蛋 1325962b93 init db 2025-01-12 15:28:01 +08:00
辉鸭蛋 e06527ce85 + 2025-01-09 23:06:48 +08:00
辉鸭蛋 8b0ced3dc5 up++ 2025-01-09 22:43:49 +08:00
辉鸭蛋 2ea810f0a1 up 2025-01-09 22:22:22 +08:00
辉鸭蛋 c25c5bef8a only update 2025-01-09 22:03:28 +08:00
辉鸭蛋 72fb84573c new TouchInput detect 2025-01-09 21:27:36 +08:00
辉鸭蛋 53fdd50a47 update 2025-01-08 01:12:23 +08:00
辉鸭蛋 f9cddb66b9 上传 2025-01-07 23:57:10 +08:00
辉鸭蛋 dc7f4dd45d update 2025-01-06 23:26:38 +08:00
辉鸭蛋 3a45def9ff check hash 2025-01-06 00:13:49 +08:00
辉鸭蛋 7de3d7364f new m 2025-01-05 22:29:21 +08:00
辉鸭蛋 353a3f5950 update UnityLogGameLocator 2025-01-05 22:07:39 +08:00
辉鸭蛋 b989e15019 upload 2025-01-05 21:47:30 +08:00
辉鸭蛋 5100dfa496 fix genshin install path get
(cherry picked from commit a57aed9ce7)
2025-01-05 17:02:06 +08:00
辉鸭蛋 e2a4383f2c tos init 2025-01-05 17:02:02 +08:00
辉鸭蛋 b1a59c47a3 version 2025-01-05 02:57:29 +08:00
辉鸭蛋 8f91858b8d new record 2025-01-05 02:38:41 +08:00
辉鸭蛋 bc1dfa8f12 tos test 2025-01-04 15:07:09 +08:00
辉鸭蛋 1f7aee994e 1 2025-01-03 03:16:04 +08:00
辉鸭蛋 79bea6b149 game settings 2025-01-03 03:02:00 +08:00
辉鸭蛋 5ece7eaaee rename to video 2024-12-29 20:01:28 +08:00
辉鸭蛋 c9d1817ac4 10.38.3 2024-12-29 18:35:21 +08:00
辉鸭蛋 351a3cb270 utc+8 2024-12-29 18:30:48 +08:00
辉鸭蛋 9c93cb465d fix path 2024-12-29 14:07:45 +08:00
辉鸭蛋 a78d31af06 .2 2024-12-28 18:23:11 +08:00
辉鸭蛋 ec56692f8a + 2024-12-28 18:03:05 +08:00
辉鸭蛋 cbd33a15ef obs 2024-12-28 14:11:16 +08:00
辉鸭蛋 03f0e46784 move pc.json 2024-12-28 10:53:36 +08:00
辉鸭蛋 7e599634d6 fix install path get
(cherry picked from commit c9634abebb)
2024-12-27 02:39:55 +08:00
辉鸭蛋 d396b15acb fix 2024-12-27 02:30:03 +08:00
辉鸭蛋 a01f51b226 fixed 2024-12-27 02:11:01 +08:00
辉鸭蛋 8b31a64fbe new game path loader
(cherry picked from commit dc853f2307)
2024-12-27 01:02:26 +08:00
辉鸭蛋 9633c8a995 10.37.9 2024-12-26 02:31:52 +08:00
辉鸭蛋 6df528b142 pc info 2024-12-26 02:31:23 +08:00
辉鸭蛋 3ed01a5d46 pc info 2024-12-26 01:10:21 +08:00
辉鸭蛋 7af3833564 set dpi 2024-12-25 01:36:36 +08:00
辉鸭蛋 01f5bfb24a set res 2024-12-25 01:03:47 +08:00
辉鸭蛋 58019c428e ui 2024-12-25 00:52:12 +08:00
辉鸭蛋 acdbaeb31b 10.37.7 2024-12-24 00:09:00 +08:00
辉鸭蛋 54f7aab45c setting 2024-12-24 00:08:34 +08:00
辉鸭蛋 839343cebf SysParams 2024-12-23 23:32:25 +08:00
辉鸭蛋 6fbae881de check 2024-12-23 23:27:26 +08:00
辉鸭蛋 e36257e7b4 fix 2024-12-23 23:16:32 +08:00
辉鸭蛋 5ff8b30dc1 jsonl1 2024-12-23 22:29:10 +08:00
辉鸭蛋 da8fc4a89e 1222 2024-12-23 02:51:22 +08:00
辉鸭蛋 ef0ced332c params 2024-12-19 01:16:59 +08:00
辉鸭蛋 21dedd3ebf folder 2024-12-19 01:05:29 +08:00
辉鸭蛋 17f678294e use system tick count 2024-12-19 00:35:24 +08:00
辉鸭蛋 4f675068a9 new mouse key hook 2024-12-18 23:17:52 +08:00
辉鸭蛋 cc615a6d7a mouse move by 2024-12-18 02:34:09 +08:00
辉鸭蛋 f8994f2ebc fix mask 2024-12-18 02:22:40 +08:00
辉鸭蛋 ed9768ac78 test 2024-12-17 02:25:47 +08:00
辉鸭蛋 b483ec2d84 play with merge event 2024-12-17 01:30:45 +08:00
辉鸭蛋 0d56fa6c7e fix bug 2024-12-17 01:05:24 +08:00
辉鸭蛋 83f8f78203 fix all 2024-12-16 23:56:30 +08:00
辉鸭蛋 e6bac7e72c add ffmpeg recorder 2024-12-16 08:55:08 +08:00
辉鸭蛋 fa3e7fccb0 add sharp avi 2024-12-15 17:48:30 +08:00
121 changed files with 10450 additions and 514 deletions

No files matched your search

+10
View File
@@ -19,6 +19,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact.Test",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.WindowsInput", "Fischless.WindowsInput\Fischless.WindowsInput.csproj", "{9D00BC7A-9280-4AC9-8951-4502EDB71B76}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MouseKeyHook", "Common\MouseKeyHook\MouseKeyHook.csproj", "{F52AA97E-180A-40ED-8F2B-09080171D6C7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -83,6 +85,14 @@ Global
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|Any CPU.Build.0 = Release|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.ActiveCfg = Release|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.Build.0 = Release|x64
{F52AA97E-180A-40ED-8F2B-09080171D6C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F52AA97E-180A-40ED-8F2B-09080171D6C7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F52AA97E-180A-40ED-8F2B-09080171D6C7}.Debug|x64.ActiveCfg = Debug|Any CPU
{F52AA97E-180A-40ED-8F2B-09080171D6C7}.Debug|x64.Build.0 = Debug|Any CPU
{F52AA97E-180A-40ED-8F2B-09080171D6C7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F52AA97E-180A-40ED-8F2B-09080171D6C7}.Release|Any CPU.Build.0 = Release|Any CPU
{F52AA97E-180A-40ED-8F2B-09080171D6C7}.Release|x64.ActiveCfg = Release|Any CPU
{F52AA97E-180A-40ED-8F2B-09080171D6C7}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+17 -12
View File
@@ -22,6 +22,8 @@ using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using BetterGenshinImpact.Helpers.Device;
using BetterGenshinImpact.Service.Singletons;
using BetterGenshinImpact.View.Pages.View;
using BetterGenshinImpact.ViewModel.Pages.OneDragon;
using BetterGenshinImpact.ViewModel.Pages.View;
@@ -41,10 +43,7 @@ public partial class App : Application
.CheckIntegration()
.UseElevated()
.UseSingleInstance("BetterGI")
.ConfigureLogging(builder =>
{
builder.ClearProviders();
})
.ConfigureLogging(builder => { builder.ClearProviders(); })
.ConfigureServices(
(context, services) =>
{
@@ -157,6 +156,8 @@ public partial class App : Application
/// </summary>
protected override async void OnStartup(StartupEventArgs e)
{
StartEndSingleton.Instance.OnStartup();
base.OnStartup(e);
try
@@ -182,6 +183,7 @@ public partial class App : Application
/// </summary>
protected override async void OnExit(ExitEventArgs e)
{
StartEndSingleton.Instance.OnExit();
base.OnExit(e);
await _host.StopAsync();
@@ -263,6 +265,9 @@ public partial class App : Application
{
e = e.InnerException;
}
var logger = GetLogger<App>();
logger.LogError("出现未捕获的异常,请切换到软件界面查看详情!{Exception}", e.Message);
try
{
@@ -273,16 +278,16 @@ public partial class App : Application
// Fallback.
System.Windows.Forms.MessageBox.Show(
$"""
程序异常:{e.Source}
--
{e.StackTrace}
--
{e.Message}
"""
程序异常:{e.Source}
--
{e.StackTrace}
--
{e.Message}
"""
);
}
// log
GetLogger<App>().LogDebug(e, "UnHandle Exception");
logger.LogDebug(e, "UnHandle Exception");
}
}
}
+26 -2
View File
@@ -10,7 +10,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\Images\logo.ico</ApplicationIcon>
<AssemblyName>BetterGI</AssemblyName>
<AssemblyVersion>0.37.5</AssemblyVersion>
<AssemblyVersion>10.39.5</AssemblyVersion>
<Platforms>x64</Platforms>
<DebugType>embedded</DebugType>
</PropertyGroup>
@@ -42,12 +42,16 @@
<ItemGroup>
<PackageReference Include="AvalonEdit" Version="6.3.0.90" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="LiteDB" Version="5.0.21" />
<PackageReference Include="MediaInfo.Wrapper.Core" Version="21.9.3" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.DirectML" Version="1.18.1" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.18.1" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
<PackageReference Include="NAudio" Version="2.2.1" />
<PackageReference Include="obs-websocket-dotnet" Version="5.0.0.3" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.8.0.20230708" />
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.8.0.20230708" />
@@ -55,7 +59,7 @@
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.122" />
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.5" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.5" />
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
<!-- <PackageReference Include="MouseKeyHook" Version="5.7.1" />-->
<PackageReference Include="PresentMonFps" Version="2.0.5" />
<PackageReference Include="Sdcb.PaddleInference" Version="2.5.0.1" />
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.openblas" Version="2.5.1" />
@@ -65,10 +69,14 @@
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
<PackageReference Include="SharpAvi" Version="3.0.1" />
<PackageReference Include="System.IO.Hashing" Version="8.0.0" />
<PackageReference Include="System.Management" Version="9.0.0" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="9.0.0" />
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.0.2" />
<PackageReference Include="Vanara.PInvoke.User32" Version="4.0.2" />
<PackageReference Include="Volcengine.TOS.SDK.NetCore" Version="2.1.8" />
<PackageReference Include="WPF-UI" Version="3.0.5" />
<PackageReference Include="WPF-UI.Tray" Version="3.0.5" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.23" />
@@ -83,6 +91,7 @@
<ProjectReference Include="..\Fischless.GameCapture\Fischless.GameCapture.csproj" />
<ProjectReference Include="..\Fischless.HotkeyCapture\Fischless.HotkeyCapture.csproj" />
<ProjectReference Include="..\Fischless.WindowsInput\Fischless.WindowsInput.csproj" />
<ProjectReference Include="..\Common\MouseKeyHook\MouseKeyHook.csproj" />
</ItemGroup>
<ItemGroup>
@@ -148,4 +157,19 @@
<Folder Include="User\AutoPathing\" />
</ItemGroup>
<ItemGroup>
<Page Update="View\Windows\UploadDialog.xaml">
<Generator>MSBuild:Compile</Generator>
<XamlRuntime>Wpf</XamlRuntime>
<SubType>Designer</SubType>
</Page>
</ItemGroup>
<ItemGroup>
<Compile Update="View\Windows\UploadDialog.xaml.cs">
<SubType>Code</SubType>
<DependentUpon>UploadDialog.xaml</DependentUpon>
</Compile>
</ItemGroup>
</Project>
@@ -177,6 +177,7 @@ public partial class AllConfig : ObservableObject
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
RecordConfig.PropertyChanged += OnAnyPropertyChanged;
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
}
@@ -26,4 +26,32 @@ public partial class CommonConfig : ObservableObject
/// </summary>
[ObservableProperty]
private bool _exitToTray;
[ObservableProperty]
private bool _processCheckEnabled = true;
[ObservableProperty]
private string _ffmpegCommand = " -f gdigrab -framerate 60 -use_wallclock_as_timestamps 1 -i title=原神 -pix_fmt yuv420p -c:v libx264 -preset ultrafast -f segment -segment_time 1800 -reset_timestamps 1 -strftime 1 ";
// 启动时修改分辨率
[ObservableProperty]
private bool _changeResolutionOnStart = true;
// 关闭时还原分辨率
[ObservableProperty]
private bool _restoreResolutionOnExit = false;
// 录制工具 ffmpeg/obs
[ObservableProperty]
private string _recorder = "obs";
// 用户姓名
[ObservableProperty]
private string _userName = "";
// 用户UID
[ObservableProperty]
private string _uid = "";
}
@@ -25,7 +25,7 @@ public partial class GenshinStartConfig : ObservableObject
/// 原神启动参数
/// </summary>
[ObservableProperty]
private string _genshinStartArgs = "";
private string _genshinStartArgs = "-screen-width 1920 -screen-height 1080 -popupwindow";
/// <summary>
/// 原神安装路径
@@ -38,4 +38,5 @@ public partial class GenshinStartConfig : ObservableObject
/// </summary>
[ObservableProperty]
private bool _linkedStartEnabled = true;
}
@@ -207,7 +207,7 @@ public partial class HotKeyConfig : ObservableObject
// 键鼠录制/停止
[ObservableProperty]
private string _keyMouseMacroRecordHotkey = "";
private string _keyMouseMacroRecordHotkey = "F12";
[ObservableProperty]
private string _keyMouseMacroRecordHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
@@ -56,7 +56,7 @@ public partial class MaskWindowConfig : ObservableObject
/// 显示状态指示
/// </summary>
[ObservableProperty]
private bool _showStatus = true;
private bool _showStatus = false;
/// <summary>
/// UID遮盖是否启用
@@ -24,4 +24,16 @@ public partial class RecordConfig : ObservableObject
/// </summary>
[ObservableProperty]
private bool _isRecordCameraOrientation = false;
/// <summary>
/// 通过派蒙判断是否在主界面
/// </summary>
[ObservableProperty]
private bool _paimonSwitchEnabled = false;
/// <summary>
/// 使用桌面音频
/// </summary>
[ObservableProperty]
private bool _useDesktopEnabled = false;
}
@@ -1,6 +1,7 @@
using BetterGenshinImpact.Core.Recorder;
using SharpDX.DirectInput;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
@@ -41,8 +41,8 @@ public class MouseKeyMonitor
// Note: for the application hook, use the Hook.AppEvents() instead
_globalHook = Hook.GlobalEvents();
_globalHook.KeyDown += GlobalHookKeyDown;
_globalHook.KeyUp += GlobalHookKeyUp;
_globalHook.KeyDownExt += GlobalHookKeyDown;
_globalHook.KeyUpExt += GlobalHookKeyUp;
_globalHook.MouseDownExt += GlobalHookMouseDownExt;
_globalHook.MouseUpExt += GlobalHookMouseUpExt;
_globalHook.MouseMoveExt += GlobalHookMouseMoveExt;
@@ -59,9 +59,11 @@ public class MouseKeyMonitor
_fTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(User32.VK.VK_F); };
}
private void GlobalHookKeyDown(object? sender, KeyEventArgs e)
private void GlobalHookKeyDown(object? sender, KeyEventArgsExt e)
{
// Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
// Debug.WriteLine(Kernel32.GetTickCount());
// Debug.WriteLine(System.Environment.TickCount);
// Debug.WriteLine("KeyDown: \t{0} \tIsKeyDown:{1} \tIsKeyUp:{2} \t Time:{3}", e.KeyCode, e.IsKeyDown, e.IsKeyUp, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e);
// 热键按下事件
@@ -97,7 +99,7 @@ public class MouseKeyMonitor
}
}
private void GlobalHookKeyUp(object? sender, KeyEventArgs e)
private void GlobalHookKeyUp(object? sender, KeyEventArgsExt e)
{
// Debug.WriteLine("KeyUp: \t{0}", e.KeyCode);
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e);
@@ -170,7 +172,7 @@ public class MouseKeyMonitor
private void GlobalHookMouseWheelExt(object? sender, MouseEventExtArgs e)
{
Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t Delta: {2};\t System Timestamp: {3}", e.Button, e.Location, e.Delta, e.Timestamp);
// Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t Delta: {2};\t System Timestamp: {3}", e.Button, e.Location, e.Delta, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseWheel(e);
}
@@ -178,8 +180,8 @@ public class MouseKeyMonitor
{
if (_globalHook != null)
{
_globalHook.KeyDown -= GlobalHookKeyDown;
_globalHook.KeyUp -= GlobalHookKeyUp;
_globalHook.KeyDownExt -= GlobalHookKeyDown;
_globalHook.KeyUpExt -= GlobalHookKeyUp;
_globalHook.MouseDownExt -= GlobalHookMouseDownExt;
_globalHook.MouseUpExt -= GlobalHookMouseUpExt;
_globalHook.MouseMoveExt -= GlobalHookMouseMoveExt;
@@ -9,8 +9,15 @@ using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Video;
using BetterGenshinImpact.Core.Video.obs;
using NAudio.Wave;
using SharpAvi;
using Vanara.PInvoke;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Recorder;
@@ -19,7 +26,11 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
{
private readonly ILogger<GlobalKeyMouseRecord> _logger = App.GetLogger<GlobalKeyMouseRecord>();
private KeyMouseRecorder? _recorder;
private KeyMouseRecorderJsonLine? _recorder;
// private SharpAviRecorder _sharpAviRecorder;
private IVideoRecorder? _videoRecorder;
private readonly Dictionary<Keys, bool> _keyDownState = [];
@@ -29,6 +40,10 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
private bool _isInMainUi = false; // 是否在主界面
private bool _paimonSwitchEnabled = false; // 是否启用派蒙切换
// private string _keyMouseMacroRecordHotkey = "";
public KeyMouseRecorderStatus Status { get; set; } = KeyMouseRecorderStatus.Stop;
public GlobalKeyMouseRecord()
@@ -37,7 +52,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
_timer.Interval = 50; // ms
}
public async Task StartRecord()
public async Task StartRecord(string fileName)
{
if (!TaskContext.Instance().IsInitialized)
{
@@ -51,77 +66,122 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
return;
}
// _keyMouseMacroRecordHotkey = TaskContext.Instance().Config.HotKeyConfig.KeyMouseMacroRecordHotkey;
_paimonSwitchEnabled = TaskContext.Instance().Config.RecordConfig.PaimonSwitchEnabled;
Status = KeyMouseRecorderStatus.Start;
SystemControl.ActivateWindow();
_logger.LogInformation("录制:{Text}", "实时任务已暂停");
_logger.LogInformation("注意:录制时遇到主界面(鼠标永远在界面中心)和其他界面(鼠标可自由移动,比如地图等)的切换,请把手离开鼠标等待录制模式切换日志");
// _logger.LogInformation("录制:{Text}", "实时任务已暂停");
// _logger.LogInformation("注意:录制时遇到主界面(鼠标永远在界面中心)和其他界面(鼠标可自由移动,比如地图等)的切换,请把手离开鼠标等待录制模式切换日志");
for (var i = 3; i >= 1; i--)
// 先实例化
// _sharpAviRecorder = new SharpAviRecorder( Path.Combine(videoPath, $"{DateTime.Now:yyyyMMddHH_mmssffff.avi}"),
// CodecIds.MotionJpeg, 90, 0, SupportedWaveFormat.WAVE_FORMAT_44M16, false, 0);
_videoRecorder = VideoRecorderFactory.Create(TaskContext.Instance().Config.CommonConfig.Recorder, fileName);
_directInputMonitor = new DirectInputMonitor();
var recorderTmp = new KeyMouseRecorderJsonLine(fileName);
// TaskTriggerDispatcher.Instance().StopTimer();
// for (var i = 3; i >= 1; i--)
// {
// _logger.LogInformation("{Sec}秒后启动录制...", i);
// await Task.Delay(1000);
// }
if (_paimonSwitchEnabled)
{
_logger.LogInformation("{Sec}秒后启动录制...", i);
await Task.Delay(1000);
_timer.Start();
}
TaskTriggerDispatcher.Instance().StopTimer();
_timer.Start();
var tmpTime = DateTime.Now;
var sw = new Stopwatch();
sw.Start();
long current;
_recorder = new KeyMouseRecorder();
_directInputMonitor = new DirectInputMonitor();
_directInputMonitor.Start();
_logger.LogInformation("从开始到directInput启动累计耗时ms:{Text}", sw.ElapsedMilliseconds);
var videoEnabled = _videoRecorder.Start();
_logger.LogInformation("从开始到视频录制启动累计耗时(OBS是WS通知完成耗时,并非实际录制时间)ms:{Text}", sw.ElapsedMilliseconds);
_recorder = recorderTmp.Start();
_recorder.AppendStartInfo();
_logger.LogInformation("从开始到键鼠录制启动累计耗时ms:{Text}", sw.ElapsedMilliseconds);
sw.Stop();
ObsLogFileProcessor.FindStartTime(fileName, tmpTime);
Status = KeyMouseRecorderStatus.Recording;
_logger.LogInformation("录制:{Text}", "已启动");
}
public string StopRecord()
public void StopRecord()
{
if (Status != KeyMouseRecorderStatus.Recording)
{
throw new InvalidOperationException("未处于录制中状态,无法停止");
}
var macro = _recorder?.ToJsonMacro() ?? string.Empty;
var sw = new Stopwatch();
sw.Start();
// var macro = _recorder?.ToJsonMacro() ?? string.Empty;
_recorder = null;
_directInputMonitor?.Stop();
_directInputMonitor?.Dispose();
_directInputMonitor = null;
_logger.LogInformation("从结束触发到键鼠录制关闭累计耗时ms:{Text}", sw.ElapsedMilliseconds);
_timer.Stop();
_videoRecorder?.Stop();
_logger.LogInformation("从结束触发到视频录制关闭累计耗时ms:{Text}", sw.ElapsedMilliseconds);
if (_timer.Enabled)
{
_timer.Stop();
}
_logger.LogInformation("录制:{Text}", "结束录制");
TaskTriggerDispatcher.Instance().StartTimer();
// TaskTriggerDispatcher.Instance().StartTimer();
Status = KeyMouseRecorderStatus.Stop;
return macro;
// return macro;
}
public void Tick(object? sender, EventArgs e)
{
var ra = TaskControl.CaptureToRectArea();
var ra = TaskControl.CaptureToRectArea(true);
var iconRa = ra.Find(ElementAssets.Instance.FriendChat);
var exist = iconRa.IsExist();
if (exist != _isInMainUi)
{
_logger.LogInformation("录制:{Text}", exist ? "进入主界面,捕获鼠标相对移动" : "离开主界面,捕获鼠标绝对移动");
}
_isInMainUi = exist;
iconRa.Dispose();
ra.Dispose();
}
public void GlobalHookKeyDown(KeyEventArgs e)
public void GlobalHookKeyDown(KeyEventArgsExt e)
{
// 排除热键
if (e.KeyCode.ToString() == TaskContext.Instance().Config.HotKeyConfig.KeyMouseMacroRecordHotkey)
{
return;
}
// if (e.KeyCode.ToString() == _keyMouseMacroRecordHotkey)
// {
// return;
// }
if (_keyDownState.TryGetValue(e.KeyCode, out var v))
{
@@ -138,17 +198,13 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
{
_keyDownState.Add(e.KeyCode, true);
}
// Debug.WriteLine($"KeyDown: {e.KeyCode}");
_recorder?.KeyDown(e);
}
public void GlobalHookKeyUp(KeyEventArgs e)
public void GlobalHookKeyUp(KeyEventArgsExt e)
{
if (e.KeyCode.ToString() == TaskContext.Instance().Config.HotKeyConfig.Test1Hotkey)
{
return;
}
if (_keyDownState.TryGetValue(e.KeyCode, out bool state) && state)
{
// Debug.WriteLine($"KeyUp: {e.KeyCode}");
@@ -171,14 +227,25 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
public void GlobalHookMouseMoveTo(MouseEventExtArgs e)
{
if (_isInMainUi)
{
return;
}
// Debug.WriteLine($"MouseMove: {e.X}, {e.Y}");
_recorder?.MouseMoveTo(e);
if (_paimonSwitchEnabled)
{
if (_isInMainUi)
{
_recorder?.MouseMoveTo(e, false);
}
else
{
_recorder?.MouseMoveTo(e, true);
}
}
else
{
_recorder?.MouseMoveTo(e, false);
}
}
public void GlobalHookMouseWheel(MouseEventExtArgs e)
{
// Debug.WriteLine($"MouseWheel: {e.Delta}");
@@ -187,12 +254,30 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
public void GlobalHookMouseMoveBy(MouseState state)
{
if (state is { X: 0, Y: 0 } || !_isInMainUi)
// Debug.WriteLine($"MouseMoveBy: {state.X}, {state.Y}");
if (state is { X: 0, Y: 0 })
{
return;
}
// Debug.WriteLine($"MouseMoveBy: {state.X}, {state.Y}");
_recorder?.MouseMoveBy(state);
var tick = Kernel32.GetTickCount();
if (_paimonSwitchEnabled)
{
if (!_isInMainUi)
{
_recorder?.MouseMoveBy(state, tick, false);
}
else
{
_recorder?.MouseMoveBy(state, tick, true);
}
}
else
{
_recorder?.MouseMoveBy(state, tick, true);
}
}
}
@@ -201,4 +286,4 @@ public enum KeyMouseRecorderStatus
Start,
Recording,
Stop
}
}
@@ -30,11 +30,12 @@ public class KeyMouseMacroPlayer
var script = JsonSerializer.Deserialize<KeyMouseScript>(macro, KeyMouseRecorder.JsonOptions) ?? throw new Exception("Failed to deserialize macro");
script.Adapt(TaskContext.Instance().SystemInfo.CaptureAreaRect, TaskContext.Instance().DpiScale);
script.Merge();
SystemControl.ActivateWindow();
if (withDelay)
{
for (var i = 3; i >= 1; i--)
for (var i = 2; i >= 1; i--)
{
TaskControl.Logger.LogInformation("{Sec}秒后进行重放...", i);
await Task.Delay(1000, ct);
@@ -0,0 +1,239 @@
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.Helpers;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fischless.WindowsInput;
using Vanara.PInvoke;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Recorder;
public class KeyMouseMacroPlayerJsonLine
{
public static async Task PlayMacro(string path, CancellationToken ct, bool withDelay = true)
{
if (!TaskContext.Instance().IsInitialized)
{
Toast.Warning("请先在启动页,启动截图器再使用本功能");
return;
}
var file = new FileInfo(path);
var infoJson = await File.ReadAllTextAsync(file.FullName, ct);
var info = JsonSerializer.Deserialize<KeyMouseScriptInfo>(infoJson, KeyMouseRecorder.JsonOptions) ?? throw new Exception("Failed to deserialize macro info");
var macroEventsLines = await File.ReadAllTextAsync(Path.Combine(file.Directory!.FullName, "macroEvents.jsonl"), ct);
List<MacroEvent> macroEvents = new();
foreach (var line in macroEventsLines.Split("\n"))
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
macroEvents.Add(JsonSerializer.Deserialize<MacroEvent>(line, KeyMouseRecorder.JsonOptions) ?? throw new Exception("Failed to deserialize macro event"));
}
// MacroEvents 需要以实际时间进行排序
macroEvents.Sort((a, b) => a.Time.CompareTo(b.Time));
// 删除为负数的时间
macroEvents.RemoveAll(m => m.Time < 0);
var script = new KeyMouseScript
{
Info = info,
MacroEvents = macroEvents
};
script.Adapt(TaskContext.Instance().SystemInfo.CaptureAreaRect, TaskContext.Instance().DpiScale);
script.Merge();
SystemControl.ActivateWindow();
if (withDelay)
{
for (var i = 2; i >= 1; i--)
{
TaskControl.Logger.LogInformation("{Sec}秒后进行重放...", i);
await Task.Delay(1000, ct);
}
TaskControl.Logger.LogInformation("开始重放");
}
await PlayMacro(script.MacroEvents, ct);
}
public static async Task PlayMacro(List<MacroEvent> macroEvents, CancellationToken ct)
{
WorkingArea = PrimaryScreen.WorkingArea;
var startTime = DateTime.UtcNow;
foreach (var e in macroEvents)
{
if (ct.IsCancellationRequested)
{
return;
}
var timeToWait = (int)(e.Time - (DateTime.UtcNow - startTime).TotalMilliseconds);
if (timeToWait < 0)
{
TaskControl.Logger.LogWarning("无法原速重放事件{Event},落后{TimeToWait}ms", e.Type.ToString(), -timeToWait);
}
else
{
await Task.Delay(timeToWait, ct);
}
switch (e.Type)
{
case MacroEventType.KeyDown:
var vkDown = (User32.VK)e.KeyCode!;
if (InputBuilder.IsExtendedKey(vkDown))
{
Simulation.SendInput.Keyboard.KeyDown(false, vkDown);
}
else
{
Simulation.SendInput.Keyboard.KeyDown(vkDown);
}
break;
case MacroEventType.KeyUp:
var vkUp = (User32.VK)e.KeyCode!;
if (InputBuilder.IsExtendedKey(vkUp))
{
Simulation.SendInput.Keyboard.KeyUp(false, vkUp);
}
else
{
Simulation.SendInput.Keyboard.KeyUp(vkUp);
}
break;
case MacroEventType.MouseDown:
var buttonMouseDown = Enum.Parse<MouseButtons>(e.MouseButton!);
var xMouseDown = ToVirtualDesktopX(e.MouseX);
var yMouseDown = ToVirtualDesktopY(e.MouseY);
switch (buttonMouseDown)
{
case MouseButtons.Left:
Simulation.SendInput.Mouse.MoveMouseTo(xMouseDown, yMouseDown).LeftButtonDown();
break;
case MouseButtons.Right:
Simulation.SendInput.Mouse.MoveMouseTo(xMouseDown, yMouseDown).RightButtonDown();
break;
case MouseButtons.Middle:
Simulation.SendInput.Mouse.MoveMouseTo(xMouseDown, yMouseDown).MiddleButtonDown();
break;
case MouseButtons.None:
break;
case MouseButtons.XButton1:
break;
case MouseButtons.XButton2:
break;
default:
throw new ArgumentOutOfRangeException();
}
break;
case MacroEventType.MouseUp:
var buttonMouseUp = Enum.Parse<MouseButtons>(e.MouseButton!);
var xMouseUp = ToVirtualDesktopX(e.MouseX);
var yMouseUp = ToVirtualDesktopY(e.MouseY);
switch (buttonMouseUp)
{
case MouseButtons.Left:
Simulation.SendInput.Mouse.MoveMouseTo(xMouseUp, yMouseUp).LeftButtonUp();
break;
case MouseButtons.Right:
Simulation.SendInput.Mouse.MoveMouseTo(xMouseUp, yMouseUp).RightButtonUp();
break;
case MouseButtons.Middle:
Simulation.SendInput.Mouse.MoveMouseTo(xMouseUp, yMouseUp).MiddleButtonUp();
break;
case MouseButtons.None:
break;
case MouseButtons.XButton1:
break;
case MouseButtons.XButton2:
break;
default:
throw new ArgumentOutOfRangeException();
}
break;
case MacroEventType.MouseMoveTo:
Simulation.SendInput.Mouse.MoveMouseTo(ToVirtualDesktopX(e.MouseX), ToVirtualDesktopY(e.MouseY));
break;
case MacroEventType.MouseWheel:
var num = (int)(e.MouseY / 120.0);
if (num != 0)
{
// 不支持多次的场景,但是不会出现这种情况
Simulation.SendInput.Mouse.VerticalScroll(num);
}
break;
case MacroEventType.MouseMoveBy:
if (e.CameraOrientation != null)
{
var cao = CameraOrientation.Compute(TaskControl.CaptureToRectArea().SrcMat);
var diff = ((int)Math.Round(cao) - (int)e.CameraOrientation + 180) % 360 - 180;
diff += diff < -180 ? 360 : 0;
//过滤一下特别大的角度偏差
if (diff != 0 && diff < 8 && diff > -8)
{
TaskControl.Logger.LogWarning("视角重放偏差{diff}°,尝试修正", diff);
e.MouseX -= diff;
}
}
Simulation.SendInput.Mouse.MoveMouseBy(e.MouseX, e.MouseY);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
public static Size WorkingArea;
public static double ToVirtualDesktopX(int x)
{
return x * 65535 * 1d / WorkingArea.Width;
}
public static double ToVirtualDesktopY(int y)
{
return y * 65535 * 1d / WorkingArea.Height;
}
}
@@ -6,9 +6,13 @@ using Gma.System.MouseKeyHook;
using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows.Forms;
using BetterGenshinImpact.Helpers;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Recorder;
@@ -16,7 +20,10 @@ public class KeyMouseRecorder
{
public List<MacroEvent> MacroEvents { get; } = [];
public DateTime StartTime { get; set; } = DateTime.UtcNow;
public List<MacroEvent> MouseMoveToMacroEvents { get; } = [];
public List<MacroEvent> MouseMoveByMacroEvents { get; } = [];
public uint StartTick { get; set; } = Kernel32.GetTickCount();
public DateTime LastOrientationDetection { get; set; } = DateTime.UtcNow;
@@ -34,160 +41,122 @@ public class KeyMouseRecorder
public string ToJsonMacro()
{
// MacroEvents 需要以实际时间进行排序
MacroEvents.Sort((a, b) => a.Time.CompareTo(b.Time));
// 删除为负数的时间
MacroEvents.RemoveAll(m => m.Time < 0);
var startTime = EnvironmentUtil.LastBootUpTime()! + TimeSpan.FromMilliseconds(StartTick);
var rect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
// 合并鼠标移动事件
var mergedMacroEvents = new List<MacroEvent>();
MacroEvent? currentMerge = null;
foreach (var macroEvent in MacroEvents)
{
if (currentMerge == null)
{
currentMerge = macroEvent;
continue;
}
if (currentMerge.Type != macroEvent.Type)
{
mergedMacroEvents.Add(currentMerge);
currentMerge = macroEvent;
continue;
}
switch (macroEvent.Type)
{
case MacroEventType.MouseMoveTo:
// 控制合并时间片段长度
if (macroEvent.Time - currentMerge.Time > MergedEventTimeMax)
{
mergedMacroEvents.Add(currentMerge);
currentMerge = macroEvent;
break;
}
// 合并为最后一个事件的位置,避免丢步
currentMerge.MouseX = macroEvent.MouseX;
currentMerge.MouseY = macroEvent.MouseY;
break;
case MacroEventType.MouseMoveBy:
if (macroEvent.Time - currentMerge.Time > MergedEventTimeMax)
{
mergedMacroEvents.Add(currentMerge);
currentMerge = macroEvent;
break;
}
// 相对位移量相加
currentMerge.MouseX += macroEvent.MouseX;
currentMerge.MouseY += macroEvent.MouseY;
if (macroEvent.CameraOrientation != null)
{
currentMerge.CameraOrientation = macroEvent.CameraOrientation;
}
break;
default:
mergedMacroEvents.Add(currentMerge);
mergedMacroEvents.Add(macroEvent);
currentMerge = null;
break;
}
}
KeyMouseScript keyMouseScript = new()
{
MacroEvents = mergedMacroEvents,
MacroEvents = MacroEvents,
MouseMoveByMacroEvents = MouseMoveByMacroEvents,
MouseMoveToMacroEvents = MouseMoveToMacroEvents,
Info = new KeyMouseScriptInfo
{
X = rect.X,
Y = rect.Y,
Width = rect.Width,
Height = rect.Height,
RecordDpi = TaskContext.Instance().DpiScale
RecordDpi = TaskContext.Instance().DpiScale,
StartTime = $"{startTime:yyyy-MM-dd HH:mm:ss:ffff}",
StartTimeUnixTimestamp = (startTime - new DateTime(1970, 1, 1)).Value.TotalNanoseconds.ToString("F0")
}
};
return JsonSerializer.Serialize(keyMouseScript, JsonOptions);
}
public void KeyDown(KeyEventArgs e)
public void KeyDown(KeyEventArgsExt e)
{
var time = e.Timestamp - StartTick;
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.KeyDown,
KeyCode = e.KeyValue,
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
Time = time
});
}
public void KeyUp(KeyEventArgs e)
public void KeyUp(KeyEventArgsExt e)
{
var time = e.Timestamp - StartTick;
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.KeyUp,
KeyCode = e.KeyValue,
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
Time = time
});
}
public void MouseDown(MouseEventExtArgs e)
{
var time = e.Timestamp - StartTick;
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseDown,
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
Time = time
});
}
public void MouseUp(MouseEventExtArgs e)
{
var time = e.Timestamp - StartTick;
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseUp,
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
Time = time
});
}
public void MouseMoveTo(MouseEventExtArgs e)
public void MouseMoveTo(MouseEventExtArgs e, bool save = false)
{
MacroEvents.Add(new MacroEvent
var time = e.Timestamp - StartTick;
var mEvent = new MacroEvent
{
Type = MacroEventType.MouseMoveTo,
MouseX = e.X,
MouseY = e.Y,
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
});
Time = time
};
MouseMoveToMacroEvents.Add(mEvent);
if (save)
{
MacroEvents.Add(mEvent);
}
}
public void MouseWheel(MouseEventExtArgs e)
{
var time = e.Timestamp - StartTick;
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseWheel,
MouseY = e.Delta, // 120 的倍率
Time = (DateTime.UtcNow - StartTime).TotalMilliseconds
Time = time
});
}
public void MouseMoveBy(MouseState state)
public void MouseMoveBy(MouseState state, uint tick, bool save = false)
{
var now = DateTime.UtcNow;
int? cao = null;
if (TaskContext.Instance().Config.RecordConfig.IsRecordCameraOrientation)
{
if ((now - LastOrientationDetection).TotalMilliseconds > 100.0)
{
LastOrientationDetection = now;
cao = (int)Math.Round(CameraOrientation.Compute(TaskControl.CaptureToRectArea().SrcMat));
}
}
MacroEvents.Add(new MacroEvent
var mEvent = new MacroEvent
{
Type = MacroEventType.MouseMoveBy,
MouseX = state.X,
MouseY = state.Y,
Time = (now - StartTime).TotalMilliseconds,
CameraOrientation = cao,
});
Time = tick - 5,
};
MouseMoveByMacroEvents.Add(mEvent);
if (save)
{
MacroEvents.Add(mEvent);
}
}
}
}
@@ -0,0 +1,220 @@
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Map;
using Gma.System.MouseKeyHook;
using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Windows.Forms;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Helpers;
using Microsoft.Extensions.Logging;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Recorder;
public class KeyMouseRecorderJsonLine
{
public KeyMouseScriptInfo Info { get; set; }
private readonly Channel<MacroEvent> _macroEventsChannel = Channel.CreateUnbounded<MacroEvent>();
private readonly Channel<MacroEvent> _mouseMoveToMacroEventsChannel = Channel.CreateUnbounded<MacroEvent>();
private readonly Channel<MacroEvent> _mouseMoveByMacroEventsChannel = Channel.CreateUnbounded<MacroEvent>();
private readonly Task _consumerTask;
public uint StartTick { get; set; } = Kernel32.GetTickCount();
public static readonly JsonSerializerOptions JsonOptions = new()
{
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
string _path;
public KeyMouseRecorderJsonLine(string folderName)
{
_path = Global.Absolute($@"User\KeyMouseScript\{folderName}\");
// var bootTime = EnvironmentUtil.LastBootUpTime();
// if (bootTime == null)
// {
// TaskControl.Logger.LogWarning("无法获取系统启动时间");
// }
// else
// {
// startTime = bootTime.Value + TimeSpan.FromMilliseconds(StartTick);
// }
var rect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
Info = new KeyMouseScriptInfo
{
X = rect.X,
Y = rect.Y,
Width = rect.Width,
Height = rect.Height,
RecordDpi = TaskContext.Instance().DpiScale,
SysParams = RecordContext.Instance.SysParams,
BgiVersion = Global.Version
};
_consumerTask = Task.Run(async () => await ConsumeEventsAsync(_path));
}
public KeyMouseRecorderJsonLine Start()
{
StartTick = Kernel32.GetTickCount();
return this;
}
public void AppendStartInfo()
{
Task.Run(() =>
{
DateTime startTime = DateTime.Now;
Info.StartTime = $"{startTime:yyyy-MM-dd HH:mm:ss:ffff}";
Info.StartTimeUnixTimestamp = (startTime.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalNanoseconds.ToString("F0");
var infoJson = JsonSerializer.Serialize(Info, JsonOptions);
File.WriteAllText(Path.Combine(_path, $"systemInfo.json"), infoJson);
});
}
private async Task ConsumeEventsAsync(string path)
{
var tasks = new List<Task>
{
ConsumeChannelAsync(_macroEventsChannel, Path.Combine(path, "macroEvents.jsonl")),
ConsumeChannelAsync(_mouseMoveToMacroEventsChannel, Path.Combine(path, "mouseMoveToMacroEvents.jsonl")),
ConsumeChannelAsync(_mouseMoveByMacroEventsChannel, Path.Combine(path, "mouseMoveByMacroEvents.jsonl"))
};
await Task.WhenAll(tasks);
}
private async Task ConsumeChannelAsync(Channel<MacroEvent> channel, string filePath)
{
await using var stream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None);
await using var writer = new StreamWriter(stream);
await foreach (var macroEvent in channel.Reader.ReadAllAsync())
{
var json = JsonSerializer.Serialize(macroEvent, JsonOptions);
await writer.WriteLineAsync(json);
await writer.FlushAsync();
}
}
private void AddEvent(Channel<MacroEvent> channel, MacroEvent macroEvent)
{
channel.Writer.TryWrite(macroEvent);
}
public void KeyDown(KeyEventArgsExt e)
{
var time = e.Timestamp - StartTick;
AddEvent(_macroEventsChannel, new MacroEvent
{
Type = MacroEventType.KeyDown,
KeyCode = e.KeyValue,
Time = time
});
}
public void KeyUp(KeyEventArgsExt e)
{
var time = e.Timestamp - StartTick;
AddEvent(_macroEventsChannel, new MacroEvent
{
Type = MacroEventType.KeyUp,
KeyCode = e.KeyValue,
Time = time
});
}
public void MouseDown(MouseEventExtArgs e)
{
var time = e.Timestamp - StartTick;
AddEvent(_macroEventsChannel, new MacroEvent
{
Type = MacroEventType.MouseDown,
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = time
});
}
public void MouseUp(MouseEventExtArgs e)
{
var time = e.Timestamp - StartTick;
AddEvent(_macroEventsChannel, new MacroEvent
{
Type = MacroEventType.MouseUp,
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = time
});
}
public void MouseMoveTo(MouseEventExtArgs e, bool save = false)
{
var time = e.Timestamp - StartTick;
var mEvent = new MacroEvent
{
Type = MacroEventType.MouseMoveTo,
MouseX = e.X,
MouseY = e.Y,
Time = time
};
AddEvent(_mouseMoveToMacroEventsChannel, mEvent);
if (save)
{
AddEvent(_macroEventsChannel, mEvent);
}
}
public void MouseWheel(MouseEventExtArgs e)
{
var time = e.Timestamp - StartTick;
AddEvent(_macroEventsChannel, new MacroEvent
{
Type = MacroEventType.MouseWheel,
MouseY = e.Delta, // 120 的倍率
Time = time
});
}
public void MouseMoveBy(MouseState state, uint tick, bool save = false)
{
User32.GetCursorPos(out var p);
var mEvent = new MacroEvent
{
Type = MacroEventType.MouseMoveBy,
MouseX = state.X,
MouseY = state.Y,
Time = tick - 5 - StartTick,
MouseAbsoluteX = p.X,
MouseAbsoluteY = p.Y
};
AddEvent(_mouseMoveByMacroEventsChannel, mEvent);
if (save)
{
AddEvent(_macroEventsChannel, mEvent);
}
}
}
@@ -9,6 +9,8 @@ namespace BetterGenshinImpact.Core.Recorder.Model;
public class KeyMouseScript
{
public List<MacroEvent> MacroEvents { get; set; } = [];
public List<MacroEvent> MouseMoveByMacroEvents { get; set; } = [];
public List<MacroEvent> MouseMoveToMacroEvents { get; set; } = [];
public KeyMouseScriptInfo? Info { get; set; }
/// <summary>
@@ -38,4 +40,70 @@ public class KeyMouseScript
}
}
}
}
public void Merge()
{
// 合并鼠标移动事件
const int mergedEventTimeMax = 20;
var mergedMacroEvents = new List<MacroEvent>();
MacroEvent? currentMerge = null;
foreach (var macroEvent in MacroEvents)
{
if (currentMerge == null)
{
currentMerge = macroEvent;
continue;
}
if (currentMerge.Type != macroEvent.Type)
{
mergedMacroEvents.Add(currentMerge);
currentMerge = macroEvent;
continue;
}
switch (macroEvent.Type)
{
case MacroEventType.MouseMoveTo:
// 控制合并时间片段长度
if (macroEvent.Time - currentMerge.Time > mergedEventTimeMax)
{
mergedMacroEvents.Add(currentMerge);
currentMerge = macroEvent;
break;
}
// 合并为最后一个事件的位置,避免丢步
currentMerge.MouseX = macroEvent.MouseX;
currentMerge.MouseY = macroEvent.MouseY;
break;
case MacroEventType.MouseMoveBy:
if (macroEvent.Time - currentMerge.Time > 10)
{
mergedMacroEvents.Add(currentMerge);
currentMerge = macroEvent;
break;
}
// 相对位移量相加
currentMerge.MouseX += macroEvent.MouseX;
currentMerge.MouseY += macroEvent.MouseY;
if (macroEvent.CameraOrientation != null)
{
currentMerge.CameraOrientation = macroEvent.CameraOrientation;
}
break;
default:
mergedMacroEvents.Add(currentMerge);
mergedMacroEvents.Add(macroEvent);
currentMerge = null;
break;
}
}
MacroEvents = mergedMacroEvents;
}
}
@@ -24,4 +24,12 @@ public class KeyMouseScriptInfo
public int Height { get; set; }
public double RecordDpi { get; set; } = 1.0;
public string StartTime { get; set; } = string.Empty;
public string StartTimeUnixTimestamp { get; set; } = string.Empty;
public SysParams? SysParams { get; set; }
public string VideoSize { get; set; } = string.Empty;
}
@@ -1,4 +1,5 @@
using System;
using System.Text.Json.Serialization;
namespace BetterGenshinImpact.Core.Recorder.Model;
@@ -11,8 +12,10 @@ public class MacroEvent
public int MouseY { get; set; }
public string? MouseButton { get; set; }
public double Time { get; set; }
public int? CameraOrientation { get; set; }
public int? MouseAbsoluteX { get; set; }
public int? MouseAbsoluteY { get; set; }
}
public enum MacroEventType
@@ -0,0 +1,10 @@
using BetterGenshinImpact.Model;
namespace BetterGenshinImpact.Core.Recorder.Model;
public class RecordContext : Singleton<RecordContext>
{
public SysParams SysParams { get; set; } = new();
}
@@ -0,0 +1,24 @@
using BetterGenshinImpact.Helpers;
namespace BetterGenshinImpact.Core.Recorder.Model;
public class SysParams
{
/// <summary>
/// 提高指针精确度 是否启用
/// </summary>
public bool EnhancePointerPrecision { get; set; }
public SysParams()
{
var (mouseThreshold1, mouseThreshold2, mouseThreshold3) = EnvironmentUtil.GetMouse();
if (mouseThreshold3 > 0)
{
EnhancePointerPrecision = true;
}
else
{
EnhancePointerPrecision = false;
}
}
}
@@ -0,0 +1,142 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
using Serilog.Core;
namespace BetterGenshinImpact.Core.Video;
public class FfmpegRecorder : IVideoRecorder
{
// ffmpeg进程
private readonly Process _process;
// ffmpeg.exe实体文件路径
private static readonly string FfmpegPath = Global.Absolute(@"video\bin\ffmpeg.exe");
private readonly string _filePath;
private string _startTime = string.Empty;
public string FileName { get; set; }
public FfmpegRecorder(string fileName)
{
FileName = fileName;
if (!File.Exists(FfmpegPath))
{
throw new Exception("ffmpeg.exe不存在");
}
var folderPath = Global.Absolute($@"User\KeyMouseScript\{FileName}\");
Directory.CreateDirectory(folderPath);
_filePath = Path.Combine(folderPath, "%Y_%m_%d_%H_%M_%S.mp4");
var processInfo = new ProcessStartInfo
{
FileName = FfmpegPath,
Arguments = $"{TaskContext.Instance().Config.CommonConfig.FfmpegCommand} \"{_filePath}\"",
StandardInputEncoding = Encoding.UTF8,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
// StandardOutputEncoding = Encoding.UTF8,
};
_process = new Process { StartInfo = processInfo };
// _process.OutputDataReceived += (sender, args) => { Debug.WriteLine(args.Data); };
_process.ErrorDataReceived += (sender, args) =>
{
TaskControl.Logger.LogDebug(args.Data);
if (string.IsNullOrEmpty(_startTime))
{
if (args.Data != null && args.Data.Contains("start"))
{
string pattern = @"start:\s*(\d+\.\d+)";
Match match = Regex.Match(args.Data, pattern);
if (match.Success)
{
_startTime = match.Groups[1].Value.Replace(".", "");
TaskControl.Logger.LogInformation("ffmpeg录制: 视频起始时间戳 {Text}", _startTime);
File.WriteAllText(Path.Combine(folderPath, $"videoStartTime.txt"), _startTime + "000");
}
}
}
};
}
/// <summary>
/// 功能: 开始录制
/// </summary>
public bool Start()
{
_process.Start();
// _process.BeginOutputReadLine();
_process.BeginErrorReadLine();
TaskControl.Logger.LogInformation("ffmpeg录制: {Text}", "已启动");
return true;
}
/// <summary>
/// 功能: 停止录制
/// </summary>
public void Stop()
{
// Kernel32.AttachConsole((uint)_process.Id);
// Kernel32.SetConsoleCtrlHandler(null, true);
// Kernel32.GenerateConsoleCtrlEvent(0, 0);
// Kernel32.FreeConsole();
// AttachConsole(_process.Id);
// SetConsoleCtrlHandler(IntPtr.Zero, true);
// GenerateConsoleCtrlEvent(0, 0);
// FreeConsole();
try
{
TaskControl.Logger.LogInformation("ffmpeg录制: {Text}", "正在停止录制,请稍后...");
_process.StandardInput.WriteLine("q");
if (!_process.WaitForExit(5000))
{
_process.Kill();
}
_process.Close();
_process.Dispose();
// Thread.Sleep(3000);
// if (File.Exists(_filePath))
// {
// // 重命名文件
// var newFilePath = Global.Absolute($@"User\KeyMouseScript\{_FileName}_{_startTime}.mp4");
// File.Move(_filePath, newFilePath);
// TaskControl.Logger.LogInformation("ffmpeg录制: {Text}", $"录制完成");
// }
// else
// {
// TaskControl.Logger.LogError("ffmpeg录制: {Text}", "未找到结果文件,录制失败");
// }
}
catch (Exception e)
{
TaskControl.Logger.LogDebug(e, "ffmpeg录制: {Text}", "停止录制失败");
TaskControl.Logger.LogError("ffmpeg录制: 停止时异常:{Text}", e.Message);
}
}
public void Dispose()
{
}
}
@@ -0,0 +1,12 @@
using System;
namespace BetterGenshinImpact.Core.Video;
public interface IVideoRecorder : IDisposable
{
public bool Start();
public void Stop();
string FileName { get; set; }
}
@@ -0,0 +1,331 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recorder;
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using MediaInfo;
using Microsoft.Extensions.Logging;
using OBSWebsocketDotNet;
using OBSWebsocketDotNet.Communication;
namespace BetterGenshinImpact.Core.Video;
public class ObsRecorder : IVideoRecorder
{
private static readonly string ObsPath = Global.Absolute(@"video\bin\OBS-Studio-31.0.0-Windows\bin\64bit\obs64.exe");
private Process? _obs64Process;
private OBSWebsocket obs;
private bool isConnected = false;
private DateTime _lastRecordTime = DateTime.MinValue;
public string FileName { get; set; }
public ObsRecorder()
{
_obs64Process = StartObs();
obs = new OBSWebsocket();
// 注册连接事件处理
obs.Connected += OnConnected;
obs.Disconnected += OnDisconnected;
Connect();
}
public static Process? StartObs()
{
// 判断 OBS 是否已经启动
var list = Process.GetProcessesByName("obs64");
if (list.Length == 0)
{
// 启动 OBS 并等待启动完成
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = ObsPath,
Arguments = "--disable-shutdown-check --disable-missing-files-check --disable-updater",
WorkingDirectory = Path.GetDirectoryName(ObsPath)
};
var obs64Process = Process.Start(startInfo);
if (obs64Process != null)
{
obs64Process.WaitForInputIdle(); // Wait for the process to be ready for input
Debug.WriteLine("OBS has started and is ready for input.");
TaskControl.Logger.LogInformation("OBS: 启动完成");
return obs64Process;
}
else
{
TaskControl.Logger.LogError("OBS: 启动失败");
throw new Exception("OBS启动失败");
return null;
}
}
return list[0];
}
// 连接到 OBS
public void Connect(string url = "ws://localhost:44557", string password = "huiyadanli@789")
{
try
{
obs.ConnectAsync(url, password);
}
catch (AuthFailureException)
{
TaskControl.Logger.LogError("OBS: 验证失败 - 密码错误");
throw;
}
catch (ErrorResponseException ex)
{
TaskControl.Logger.LogError($"连接失败: {ex.Message}");
throw;
}
catch (Exception ex)
{
TaskControl.Logger.LogError($"连接失败: {ex.Message}");
throw;
}
}
// 开始录制
public bool Start()
{
for (int i = 0; i < 10; i++)
{
if (obs.IsConnected)
{
try
{
// 链接后立即变更状态
SetDefaultMixerState(TaskContext.Instance().Config.RecordConfig.UseDesktopEnabled);
obs.StartRecord();
_lastRecordTime = DateTime.Now;
TaskControl.Logger.LogInformation("OBS: ws请求开始录制,时间: {Time}", _lastRecordTime.ToString("yyyy-MM-dd HH:mm:ss.ffff"));
return true;
}
catch (ErrorResponseException ex)
{
if (ex.ErrorCode == 207)
{
TaskControl.Logger.LogInformation("207错误,等待连接 OBS 就绪...重试次数: {Count}", i + 1);
Thread.Sleep(1000);
}
else
{
TaskControl.Logger.LogError($"OBS: ws请求开始录制失败: {ex.Message}");
throw;
}
}
}
else
{
Thread.Sleep(1000);
TaskControl.Logger.LogInformation("等待连接 OBS 连接...重试次数: {Count}", i + 1);
}
}
TaskControl.Logger.LogError("OBS: 启动录制失败,未连接到 OBS");
return false;
}
// 停止录制
public void Stop()
{
if (obs.IsConnected)
{
var path = obs.StopRecord();
TaskControl.Logger.LogInformation("OBS: 停止录制录制");
var name = Path.GetFileName(path);
TaskControl.Logger.LogInformation("OBS: 文件存储在 {Path}", name);
MoveFile(name);
}
}
private void MoveFile(string name)
{
Task.Run(() =>
{
try
{
var videoPath = Global.Absolute($@"video\{name}");
var folderPath = Global.Absolute($@"User\KeyMouseScript\{FileName}\");
if (File.Exists(videoPath))
{
int i = 0;
for (i = 0; i < 10; i++)
{
if (IsFileLocked(videoPath))
{
TaskControl.Logger.LogDebug("OBS: 等待文件保存完成...重试次数: {Count}", i + 1);
Thread.Sleep(1000);
}
else
{
var targetPath = Path.Combine(folderPath, "video" + Path.GetExtension(videoPath));
File.Move(videoPath, targetPath);
TaskControl.Logger.LogInformation("OBS: 录制结果文件已移动到 {Path}", targetPath);
UpdateSystemInfo(folderPath, targetPath);
break;
}
}
if (i == 10)
{
TaskControl.Logger.LogError("未能移动录制结果文件,文件可能被占用,请手动移动,文件路径: {Path}", videoPath);
}
}
else
{
TaskControl.Logger.LogError("OBS: 未找到录制结果文件");
}
// File.WriteAllText(Path.Combine(folderPath, "videoStartTime.txt"), (_lastRecordTime.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalNanoseconds.ToString("F0"));
}
catch (Exception e)
{
TaskControl.Logger.LogError("移动录制结果文件时出现错误: {Error}", e.Message);
}
});
}
private void UpdateSystemInfo(string folderPath, string videoPath)
{
var jsonPath = Path.Combine(folderPath, $"systemInfo.json");
// 计算视频文件大小
MediaInfo.MediaInfo mediaInfo = new MediaInfo.MediaInfo();
mediaInfo.Open(videoPath);
string durationString = mediaInfo.Get(StreamKind.General, 0, "Duration");
Console.WriteLine($"视频时长: {durationString}");
// 读取json
var json = File.ReadAllText(jsonPath);
var info = JsonSerializer.Deserialize<KeyMouseScriptInfo>(json, KeyMouseRecorderJsonLine.JsonOptions);
if (info != null)
{
info.VideoSize = durationString;
// 写入json
File.WriteAllText(jsonPath, JsonSerializer.Serialize(info, KeyMouseRecorderJsonLine.JsonOptions));
}
}
static bool IsFileLocked(string filePath)
{
FileStream stream = null;
try
{
// 尝试以读取方式打开文件
stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (IOException)
{
// 捕获IOException异常表示文件被占用
return true;
}
finally
{
// 关闭文件流
stream?.Close();
}
return false;
}
private void OnConnected(object? sender, EventArgs e)
{
isConnected = true;
TaskControl.Logger.LogInformation("OBS: 成功连接");
}
private void OnDisconnected(object? sender, ObsDisconnectionInfo e)
{
if (isConnected)
{
TaskControl.Logger.LogWarning("OBS: 断开连接, 原因: {Reason}", e.DisconnectReason);
}
else
{
TaskControl.Logger.LogError("OBS: 断开连接, 原因: {Reason}", e.DisconnectReason);
}
isConnected = false;
}
public void Dispose()
{
if (obs.IsConnected)
{
obs.Disconnect();
}
}
// 预设混音器状态
public void SetDefaultMixerState(bool useDesktopSound)
{
if (useDesktopSound)
{
ChangeMixerState("桌面音频", true);
ChangeMixerState("采集原神", false);
}
else
{
ChangeMixerState("桌面音频", false);
ChangeMixerState("采集原神", true);
}
}
public void ChangeMixerState(string mixerName, bool state)
{
state = !state; // 转换成静音标识
if (!obs.IsConnected)
{
TaskControl.Logger.LogError("OBS: 未连接,无法切换混音器状态");
return;
}
try
{
bool isMute = obs.GetInputMute(mixerName);
if (isMute == state)
{
TaskControl.Logger.LogDebug("OBS: 混音器 {MixerName} 状态已经是 {State}", mixerName, state ? "静音" : "非静音");
return;
}
// 切换混音器状态
obs.SetInputMute(mixerName, state);
TaskControl.Logger.LogInformation("OBS: 混音器 {MixerName} 状态已切换为 {State}", mixerName, state ? "静音" : "非静音");
}
catch (ErrorResponseException ex)
{
TaskControl.Logger.LogError($"OBS: 切换混音器状态失败: {ex.Message}");
throw;
}
catch (Exception ex)
{
TaskControl.Logger.LogError($"OBS: 切换混音器状态时出现错误: {ex.Message}");
throw;
}
}
}
@@ -0,0 +1,258 @@
using NAudio.Wave;
using SharpAvi.Codecs;
using SharpAvi.Output;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using SharpAvi;
using FourCC = SharpAvi.FourCC;
using WaveFormat = NAudio.Wave.WaveFormat;
namespace BetterGenshinImpact.Core.Video;
public class SharpAviRecorder : IDisposable
{
// public static readonly FourCC MJPEG_IMAGE_SHARP = "IMG#";
private readonly int screenWidth;
private readonly int screenHeight;
private readonly AviWriter writer;
private readonly IAviVideoStream videoStream;
private readonly IAviAudioStream audioStream;
private readonly WaveInEvent audioSource;
private readonly Thread screenThread;
private readonly ManualResetEvent stopThread = new ManualResetEvent(false);
private readonly AutoResetEvent videoFrameWritten = new AutoResetEvent(false);
private readonly AutoResetEvent audioBlockWritten = new AutoResetEvent(false);
public SharpAviRecorder(string fileName,
FourCC codec, int quality,
int audioSourceIndex, SupportedWaveFormat audioWaveFormat, bool encodeAudio, int audioBitRate)
{
System.Windows.Media.Matrix toDevice;
using (var source = new HwndSource(new HwndSourceParameters()))
{
toDevice = source.CompositionTarget.TransformToDevice;
}
screenWidth = (int)Math.Round(SystemParameters.PrimaryScreenWidth * toDevice.M11);
screenHeight = (int)Math.Round(SystemParameters.PrimaryScreenHeight * toDevice.M22);
// Create AVI writer and specify FPS
writer = new AviWriter(fileName)
{
FramesPerSecond = 60,
EmitIndex1 = true,
};
// Create video stream
videoStream = CreateVideoStream(codec, quality);
// Set only name. Other properties were when creating stream,
// either explicitly by arguments or implicitly by the encoder used
videoStream.Name = "Screencast";
if (audioSourceIndex >= 0)
{
var waveFormat = ToWaveFormat(audioWaveFormat);
audioStream = CreateAudioStream(waveFormat, encodeAudio, audioBitRate);
// Set only name. Other properties were when creating stream,
// either explicitly by arguments or implicitly by the encoder used
audioStream.Name = "Voice";
audioSource = new WaveInEvent
{
DeviceNumber = audioSourceIndex,
WaveFormat = waveFormat,
// Buffer size to store duration of 1 frame
BufferMilliseconds = (int)Math.Ceiling(1000 / writer.FramesPerSecond),
NumberOfBuffers = 3,
};
audioSource.DataAvailable += audioSource_DataAvailable;
}
screenThread = new Thread(RecordScreen)
{
Name = typeof(SharpAviRecorder).Name + ".RecordScreen",
IsBackground = true
};
}
public void Start()
{
if (audioSource != null)
{
videoFrameWritten.Set();
audioBlockWritten.Reset();
audioSource.StartRecording();
}
screenThread.Start();
}
private IAviVideoStream CreateVideoStream(FourCC codec, int quality)
{
// Select encoder type based on FOURCC of codec
if (codec == CodecIds.Uncompressed)
{
return writer.AddUncompressedVideoStream(screenWidth, screenHeight);
}
else if (codec == CodecIds.MotionJpeg)
{
// Use M-JPEG based on WPF (Windows only)
return writer.AddMJpegWpfVideoStream(screenWidth, screenHeight, quality);
}
// else if (codec == MJPEG_IMAGE_SHARP)
// {
// // Use M-JPEG based on the SixLabors.ImageSharp package (cross-platform)
// // Included in the SharpAvi.ImageSharp package
// return writer.AddMJpegImageSharpVideoStream(screenWidth, screenHeight, quality);
// }
else
{
return writer.AddMpeg4VcmVideoStream(screenWidth, screenHeight, (double)writer.FramesPerSecond,
// It seems that all tested MPEG-4 VfW codecs ignore the quality affecting parameters passed through VfW API
// They only respect the settings from their own configuration dialogs, and Mpeg4VideoEncoder currently has no support for this
quality: quality,
codec: codec,
// Most of VfW codecs expect single-threaded use, so we wrap this encoder to special wrapper
// Thus all calls to the encoder (including its instantiation) will be invoked on a single thread although encoding (and writing) is performed asynchronously
forceSingleThreadedAccess: true);
}
}
private IAviAudioStream CreateAudioStream(WaveFormat waveFormat, bool encode, int bitRate)
{
// Create encoding or simple stream based on settings
if (encode)
{
// LAME DLL path is set in App.OnStartup()
return writer.AddMp3LameAudioStream(waveFormat.Channels, waveFormat.SampleRate, bitRate);
}
else
{
return writer.AddAudioStream(
channelCount: waveFormat.Channels,
samplesPerSecond: waveFormat.SampleRate,
bitsPerSample: waveFormat.BitsPerSample);
}
}
private static WaveFormat ToWaveFormat(SupportedWaveFormat waveFormat)
{
switch (waveFormat)
{
case SupportedWaveFormat.WAVE_FORMAT_44M16:
return new WaveFormat(44100, 16, 1);
case SupportedWaveFormat.WAVE_FORMAT_44S16:
return new WaveFormat(44100, 16, 2);
default:
throw new NotSupportedException("Wave formats other than '16-bit 44.1kHz' are not currently supported.");
}
}
public void Dispose()
{
stopThread.Set();
screenThread.Join();
if (audioSource != null)
{
audioSource.StopRecording();
audioSource.DataAvailable -= audioSource_DataAvailable;
}
// Close writer: the remaining data is written to a file and file is closed
writer.Close();
stopThread.Close();
}
private void RecordScreen()
{
var stopwatch = new Stopwatch();
var buffer = new byte[screenWidth * screenHeight * 4];
Task videoWriteTask = null;
var isFirstFrame = true;
var shotsTaken = 0;
var timeTillNextFrame = TimeSpan.Zero;
stopwatch.Start();
while (!stopThread.WaitOne(timeTillNextFrame))
{
GetScreenshot(buffer);
shotsTaken++;
// Wait for the previous frame is written
if (!isFirstFrame)
{
videoWriteTask.Wait();
videoFrameWritten.Set();
}
if (audioStream != null)
{
var signalled = WaitHandle.WaitAny(new WaitHandle[] { audioBlockWritten, stopThread });
if (signalled == 1)
break;
}
// Start asynchronous (encoding and) writing of the new frame
// Overloads with Memory parameters are available on .NET 5+
#if NET5_0_OR_GREATER
videoWriteTask = videoStream.WriteFrameAsync(true, buffer.AsMemory(0, buffer.Length));
#else
videoWriteTask = videoStream.WriteFrameAsync(true, buffer, 0, buffer.Length);
#endif
timeTillNextFrame = TimeSpan.FromSeconds(shotsTaken / (double)writer.FramesPerSecond - stopwatch.Elapsed.TotalSeconds);
if (timeTillNextFrame < TimeSpan.Zero)
timeTillNextFrame = TimeSpan.Zero;
isFirstFrame = false;
}
stopwatch.Stop();
// Wait for the last frame is written
if (!isFirstFrame)
{
videoWriteTask.Wait();
}
}
private void GetScreenshot(byte[] buffer)
{
using (var bitmap = new Bitmap(screenWidth, screenHeight))
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(screenWidth, screenHeight));
var bits = bitmap.LockBits(new Rectangle(0, 0, screenWidth, screenHeight), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
bitmap.UnlockBits(bits);
// Should also capture the mouse cursor here, but skipping for simplicity
// For those who are interested, look at http://www.codeproject.com/Articles/12850/Capturing-the-Desktop-Screen-with-the-Mouse-Cursor
}
}
private void audioSource_DataAvailable(object sender, WaveInEventArgs e)
{
var signalled = WaitHandle.WaitAny(new WaitHandle[] { videoFrameWritten, stopThread });
if (signalled == 0 && e.BytesRecorded > 0)
{
// Overloads with Span parameters are available on .NET 5+
#if NET5_0_OR_GREATER
audioStream.WriteBlock(e.Buffer.AsSpan(0, e.BytesRecorded));
#else
audioStream.WriteBlock(e.Buffer, 0, e.BytesRecorded);
#endif
audioBlockWritten.Set();
}
}
}
@@ -0,0 +1,31 @@
using System;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Video;
public class VideoRecorderFactory
{
private static ObsRecorder? _obsRecorder;
public static IVideoRecorder Create(string recorderType, string fileName)
{
switch (recorderType)
{
case "ffmpeg":
var ffmpegRecorder = new FfmpegRecorder(fileName);
return ffmpegRecorder;
case "obs":
if (_obsRecorder == null)
{
_obsRecorder = new ObsRecorder();
// TaskControl.Logger.LogInformation("当前选择使用OBS录制,OBS首次启动较慢,请耐心等待...");
}
_obsRecorder.FileName = fileName;
return _obsRecorder;
default:
throw new ArgumentException("不支持的录制工具");
}
}
}
@@ -0,0 +1,133 @@
using System;
using System.IO;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Video.obs;
public class ObsLogFileProcessor
{
private static readonly string ObsLogPath = Global.Absolute(@"video\bin\OBS-Studio-31.0.0-Windows\config\obs-studio\logs");
public static FileInfo? GetLogFilePath()
{
// 找到目录中最新的日志文件
if (!Directory.Exists(ObsLogPath))
{
TaskControl.Logger.LogError("OBS日志目录不存在");
return null;
}
var files = Directory.GetFiles(ObsLogPath, "*.txt");
if (files.Length == 0)
{
TaskControl.Logger.LogError("OBS日志文件不存在");
return null;
}
FileInfo? latestFile = null;
foreach (var file in files)
{
var fileInfo = new FileInfo(file);
if (latestFile == null || fileInfo.LastWriteTime > latestFile.LastWriteTime)
{
latestFile = fileInfo;
}
}
TaskControl.Logger.LogDebug("当前最新的OBS日志文件:{Path}", latestFile?.FullName);
return latestFile;
}
public static async Task<DateTime?> ProcessLog(DateTime? beforeStartTime)
{
var logFile = GetLogFilePath();
if (logFile == null)
{
return null;
}
// 以共享的方式读取日志文件
string content;
try
{
await using var fileStream = new FileStream(logFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new StreamReader(fileStream);
content = await reader.ReadToEndAsync();
}
catch (IOException e)
{
TaskControl.Logger.LogError("OBS日志文件读取失败:{Msg}", e.Message);
return null;
}
// 从下网上找到最近一次 = Recording Start = 关键词的行
var lines = content.Split('\n');
string? lastLine = null;
for (var i = lines.Length - 1; i >= 0; i--)
{
if (lines[i].Contains("= Recording Start ="))
{
if (beforeStartTime != null)
{
var timeStr = lines[i].Substring(0, 12);
if (DateTime.TryParse(timeStr, out var time))
{
if (time >= beforeStartTime)
{
lastLine = lines[i];
return time;
}
}
}
else
{
lastLine = lines[i];
break;
}
}
}
if (lastLine == null)
{
TaskControl.Logger.LogDebug("未找到OBS日志中录制开始关键词");
return null;
}
// 内容应该是 16:19:40.665: ==== Recording Start ===============================================
var timeStr2 = lastLine.Substring(0, 12);
// 16:19:40.665 转换到datetime
if (DateTime.TryParse(timeStr2, out var time2))
{
return time2;
}
return null;
}
public static void FindStartTime(string fileName, DateTime beforeStartTime)
{
Task.Run(async () =>
{
for (int i = 0; i < 10; i++)
{
await Task.Delay(1000);
var time = await ProcessLog(beforeStartTime);
if (time != null)
{
var t = time.Value;
TaskControl.Logger.LogInformation("OBS实际录制开始时间(来自log):{Time}", t.ToString("yyyy-MM-dd HH:mm:s.ffff"));
var folderPath = Global.Absolute($@"User\KeyMouseScript\{fileName}\");
await File.WriteAllTextAsync(Path.Combine(folderPath, "videoStartTime.txt"), (t.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalNanoseconds.ToString("F0"));
break;
}
else
{
TaskControl.Logger.LogDebug("未找到OBS实际录制开始时间,等待1s后重试");
}
}
});
}
}
@@ -59,7 +59,7 @@ namespace BetterGenshinImpact.GameTask
/// 1. 是否缓存图像
/// 2. 是否执行触发器
/// </summary>
private DispatcherCaptureModeEnum _dispatcherCacheCaptureMode = DispatcherCaptureModeEnum.NormalTrigger;
private DispatcherCaptureModeEnum _dispatcherCacheCaptureMode = DispatcherCaptureModeEnum.OnlyCacheCapture;
private static readonly object _bitmapLocker = new();
private static readonly object _triggerListLocker = new();
@@ -137,7 +137,7 @@ namespace BetterGenshinImpact.GameTask
TaskContext.Instance().Init(hWnd);
// 初始化触发器(一定要在任务上下文初始化完毕后使用)
_triggers = GameTaskManager.LoadInitialTriggers();
_triggers = [];
// 启动截图
GameCapture.Start(hWnd,
@@ -149,10 +149,10 @@ namespace BetterGenshinImpact.GameTask
);
// 捕获模式初始化配置
if (TaskContext.Instance().Config.CommonConfig.ScreenshotEnabled || TaskContext.Instance().Config.MacroConfig.CombatMacroEnabled)
{
_dispatcherCacheCaptureMode = DispatcherCaptureModeEnum.CacheCaptureWithTrigger;
}
// if (TaskContext.Instance().Config.CommonConfig.ScreenshotEnabled || TaskContext.Instance().Config.MacroConfig.CombatMacroEnabled)
// {
// _dispatcherCacheCaptureMode = DispatcherCaptureModeEnum.CacheCaptureWithTrigger;
// }
// 启动定时器
_frameIndex = 0;
@@ -211,21 +211,21 @@ namespace BetterGenshinImpact.GameTask
// 检查截图器是否初始化
var maskWindow = MaskWindow.Instance();
if (GameCapture == null || !GameCapture.IsCapturing)
{
if (!TaskContext.Instance().SystemInfo.GameProcess.HasExited)
{
_logger.LogError("截图器未初始化!");
}
else
{
_logger.LogInformation("游戏已退出,BetterGI 自动停止截图器");
}
UiTaskStopTickEvent?.Invoke(sender, e);
maskWindow.Invoke(maskWindow.Hide);
return;
}
// if (GameCapture == null || !GameCapture.IsCapturing)
// {
// if (!TaskContext.Instance().SystemInfo.GameProcess.HasExited)
// {
// _logger.LogError("截图器未初始化!");
// }
// else
// {
// _logger.LogInformation("游戏已退出,BetterGI 自动停止截图器");
// }
//
// UiTaskStopTickEvent?.Invoke(sender, e);
// maskWindow.Invoke(maskWindow.Hide);
// return;
// }
// 检查游戏是否在前台
var hasBackgroundTriggerToRun = false;
@@ -252,6 +252,16 @@ namespace BetterGenshinImpact.GameTask
{
maskWindow.Invoke(() => { maskWindow.Hide(); });
}
else
{
maskWindow.Invoke(() =>
{
if (maskWindow.IsExist())
{
maskWindow.Show();
}
});
}
}
_prevGameActive = active;
@@ -303,60 +313,60 @@ namespace BetterGenshinImpact.GameTask
}
// 帧序号自增 1分钟后归零(MaxFrameIndexSecond)
_frameIndex = (_frameIndex + 1) % (int)(CaptureContent.MaxFrameIndexSecond * 1000d / _timer.Interval);
if (_dispatcherCacheCaptureMode == DispatcherCaptureModeEnum.NormalTrigger
&& (_triggers == null || !_triggers.Exists(t => t.IsEnabled)))
{
// Debug.WriteLine("没有可用的触发器且不处于仅截屏状态, 不再进行截屏");
return;
}
var speedTimer = new SpeedTimer();
// 捕获游戏画面
var bitmap = GameCapture.Capture();
speedTimer.Record("截图");
if (bitmap == null)
{
_logger.LogWarning("截图失败!");
return;
}
if (IsOnlyCacheCapture(bitmap))
{
return;
}
// 循环执行所有触发器 有独占状态的触发器的时候只执行独占触发器
var content = new CaptureContent(bitmap, _frameIndex, _timer.Interval);
lock (_triggerListLocker)
{
var exclusiveTrigger = _triggers!.FirstOrDefault(t => t is { IsEnabled: true, IsExclusive: true });
if (exclusiveTrigger != null)
{
exclusiveTrigger.OnCapture(content);
speedTimer.Record(exclusiveTrigger.Name);
}
else
{
var runningTriggers = _triggers!.Where(t => t.IsEnabled);
if (hasBackgroundTriggerToRun)
{
runningTriggers = runningTriggers.Where(t => t.IsBackgroundRunning);
}
foreach (var trigger in runningTriggers)
{
trigger.OnCapture(content);
speedTimer.Record(trigger.Name);
}
}
}
speedTimer.DebugPrint();
content.Dispose();
// _frameIndex = (_frameIndex + 1) % (int)(CaptureContent.MaxFrameIndexSecond * 1000d / _timer.Interval);
//
// if (_dispatcherCacheCaptureMode == DispatcherCaptureModeEnum.NormalTrigger
// && (_triggers == null || !_triggers.Exists(t => t.IsEnabled)))
// {
// // Debug.WriteLine("没有可用的触发器且不处于仅截屏状态, 不再进行截屏");
// return;
// }
//
// var speedTimer = new SpeedTimer();
// // 捕获游戏画面
// var bitmap = GameCapture.Capture();
// speedTimer.Record("截图");
//
// if (bitmap == null)
// {
// _logger.LogWarning("截图失败!");
// return;
// }
//
// if (IsOnlyCacheCapture(bitmap))
// {
// return;
// }
//
// // 循环执行所有触发器 有独占状态的触发器的时候只执行独占触发器
// var content = new CaptureContent(bitmap, _frameIndex, _timer.Interval);
//
// lock (_triggerListLocker)
// {
// var exclusiveTrigger = _triggers!.FirstOrDefault(t => t is { IsEnabled: true, IsExclusive: true });
// if (exclusiveTrigger != null)
// {
// exclusiveTrigger.OnCapture(content);
// speedTimer.Record(exclusiveTrigger.Name);
// }
// else
// {
// var runningTriggers = _triggers!.Where(t => t.IsEnabled);
// if (hasBackgroundTriggerToRun)
// {
// runningTriggers = runningTriggers.Where(t => t.IsBackgroundRunning);
// }
//
// foreach (var trigger in runningTriggers)
// {
// trigger.OnCapture(content);
// speedTimer.Record(trigger.Name);
// }
// }
// }
//
// speedTimer.DebugPrint();
// content.Dispose();
}
finally
{
@@ -9,6 +9,10 @@ using System.Text.RegularExpressions;
namespace BetterGenshinImpact.Genshin.Paths;
/// <summary>
/// 已经弃用
/// </summary>
[Obsolete]
internal partial class GameExePath
{
public static readonly FrozenSet<string> GameRegistryPaths = FrozenSet.ToFrozenSet(
@@ -0,0 +1,55 @@
using System;
using System.IO;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
namespace BetterGenshinImpact.Genshin.Paths;
/// <summary>
/// https://github.com/Scighost/Starward/blob/main/src%2FStarward%2FServices%2FLauncher%2FGameLauncherService.cs#L112-L112
/// </summary>
public class RegistryGameLocator
{
public static string? GetDefaultGameInstallPath()
{
try
{
var cn = Registry.GetValue($@"HKEY_CURRENT_USER\Software\miHoYo\HYP\1_1\hk4e_cn", "GameInstallPath", null) as string;
if (!string.IsNullOrEmpty(cn))
{
var filePath = Path.Combine(cn, "YuanShen.exe");
if (File.Exists(filePath))
{
return filePath;
}
}
var global = Registry.GetValue($@"HKEY_CURRENT_USER\Software\Cognosphere\HYP\1_0\hk4e_global", "GameInstallPath", null) as string;
if (!string.IsNullOrEmpty(global))
{
var filePath = Path.Combine(global, "GenshinImpact.exe");
if (File.Exists(filePath))
{
return filePath;
}
}
var bilibili = Registry.GetValue($@"HKEY_CURRENT_USER\Software\miHoYo\HYP\standalone\14_0\hk4e_cn\umfgRO5gh5\hk4e_cn", "GameInstallPath", null) as string;
if (!string.IsNullOrEmpty(bilibili))
{
var filePath = Path.Combine(bilibili, "YuanShen.exe");
if (File.Exists(filePath))
{
return filePath;
}
}
}
catch (Exception e)
{
TaskControl.Logger.LogDebug(e, "Failed to locate game path from HYP.");
}
return null;
}
}
@@ -0,0 +1,75 @@
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Genshin.Paths;
/// <summary>
/// https://github.com/DGP-Studio/Snap.Hutao/blob/main/src/Snap.Hutao/Snap.Hutao/Service/Game/Locator/UnityLogGameLocator.cs
/// </summary>
public partial class UnityLogGameLocator
{
[GeneratedRegex(@".:(?:\\|/).+(?:GenshinImpact|YuanShen)(?=_Data)", RegexOptions.IgnoreCase)]
private static partial Regex WarmupFileLine();
public static async ValueTask<string?> LocateSingleGamePathAsync()
{
try
{
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string logFilePathOversea = Path.Combine(appDataPath, @"..\LocalLow\miHoYo\Genshin Impact\output_log.txt");
string logFilePathChinese = Path.Combine(appDataPath, @"..\LocalLow\miHoYo\原神\output_log.txt");
var p1 = await LocateGamePathAsync(logFilePathChinese).ConfigureAwait(false);
if (p1 is not null)
{
return p1;
}
return await LocateGamePathAsync(logFilePathOversea).ConfigureAwait(false);
}
catch (Exception e)
{
TaskControl.Logger.LogDebug(e, "Failed to locate game path.");
}
return null;
}
private static async ValueTask<string?> LocateGamePathAsync(string logFilePath)
{
if (!File.Exists(logFilePath))
{
return null;
}
string content;
try
{
await using var fileStream = new FileStream(logFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new StreamReader(fileStream);
content = await reader.ReadToEndAsync();
}
catch (IOException)
{
return null;
}
Match matchResult = WarmupFileLine().Match(content);
if (!matchResult.Success)
{
return null;
}
string fullPath = Path.GetFullPath($"{matchResult.Value}.exe");
if (!File.Exists(fullPath))
{
return null;
}
return fullPath;
}
}
@@ -37,8 +37,15 @@ public class InputDataSettings
public class InputDataConfig
{
// 默认值2
[JsonPropertyName("mouseSensitivity")]
public double MouseSensitivity { get; set; }
[JsonPropertyName("mouseSenseIndex")]
public int MouseSenseIndex { get; set; }
[JsonPropertyName("mouseSenseIndexY")]
public int MouseSenseIndexY { get; set; }
[JsonPropertyName("mouseFocusSenseIndex")]
public int MouseFocusSenseIndex { get; set; }
@@ -18,4 +18,10 @@ public sealed class MainJson
[JsonPropertyName("_overrideControllerMapValueList")]
public string[]? OverrideControllerMapValueList { get; set; }
//
// /// <summary>
// /// 亮度
// /// </summary>
// [JsonPropertyName("maxLuminosity")]
// public string MaxLuminosity { get; set; }
}
@@ -4,6 +4,7 @@ using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
@@ -63,6 +64,8 @@ public class SettingsContainer
{
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
});
Debug.WriteLine(Encoding.UTF8.GetString(rawCfg));
if (data is null)
{
@@ -0,0 +1,63 @@
using System;
using System.IO;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Genshin.Settings2;
public class GameSettingsChecker
{
public static bool? LoadGameSettingsAndCheck(string? path = null)
{
var settingStr = GenshinGameSettings.GetStrFromRegistry();
if (settingStr == null)
{
TaskControl.Logger.LogError("获取游戏设置失败");
MessageBox.Error("获取游戏设置失败");
return null;
}
GenshinGameSettings? settings = GenshinGameSettings.Parse(settingStr);
if (settings == null)
{
TaskControl.Logger.LogError("获取游戏设置失败");
MessageBox.Error("获取游戏设置失败");
return null;
}
GenshinGameInputSettings? inputSettings = GenshinGameInputSettings.Parse(settings.InputData);
if (inputSettings == null)
{
TaskControl.Logger.LogError("获取游戏输入设置失败");
MessageBox.Error("获取游戏输入设置失败");
return null;
}
try
{
if (settings.GammaValue != "2.200000047683716")
{
throw new Exception("检测到游戏亮度不是默认值,请将游戏亮度调整为默认值!");
}
if (inputSettings.MouseSenseIndex != 2
|| inputSettings.MouseSenseIndexY != 2
|| inputSettings.MouseFocusSenseIndex != 2
|| inputSettings.MouseFocusSenseIndexY != 2)
{
throw new Exception("检测到镜头灵敏度不是默认值,请将镜头灵敏度调整为默认值!");
}
}
catch (Exception e)
{
if (path != null)
{
File.WriteAllText(path, settingStr);
}
MessageBox.Error(e.Message);
return false;
}
return true;
}
}
@@ -0,0 +1,122 @@
using Newtonsoft.Json;
namespace BetterGenshinImpact.Genshin.Settings2;
public class GenshinGameInputSettings
{
[JsonProperty("scriptVersion")]
public string ScriptVersion { get; set; } // 脚本版本
[JsonProperty("mouseSensitivity")]
public string MouseSensitivity { get; set; } // 鼠标灵敏度
[JsonProperty("joypadSenseIndex")]
public int JoypadSenseIndex { get; set; } // 手柄灵敏度索引
[JsonProperty("joypadFocusSenseIndex")]
public int JoypadFocusSenseIndex { get; set; } // 手柄焦点灵敏度索引
[JsonProperty("joypadInvertCameraX")]
public bool JoypadInvertCameraX { get; set; } // 手柄X轴反转摄像头
[JsonProperty("joypadInvertCameraY")]
public bool JoypadInvertCameraY { get; set; } // 手柄Y轴反转摄像头
[JsonProperty("joypadInvertFocusCameraX")]
public bool JoypadInvertFocusCameraX { get; set; } // 手柄X轴反转焦点摄像头
[JsonProperty("joypadInvertFocusCameraY")]
public bool JoypadInvertFocusCameraY { get; set; } // 手柄Y轴反转焦点摄像头
[JsonProperty("mouseSenseIndex")]
public int MouseSenseIndex { get; set; } // 鼠标灵敏度索引
[JsonProperty("mouseFocusSenseIndex")]
public int MouseFocusSenseIndex { get; set; } // 鼠标焦点灵敏度索引
[JsonProperty("touchpadSenseIndex")]
public int TouchpadSenseIndex { get; set; } // 触摸板灵敏度索引
[JsonProperty("touchpadFocusSenseIndex")]
public int TouchpadFocusSenseIndex { get; set; } // 触摸板焦点灵敏度索引
[JsonProperty("enableTouchpadFocusAcceleration")]
public bool EnableTouchpadFocusAcceleration { get; set; } // 启用触摸板焦点加速度
[JsonProperty("lastJoypadDefaultScale")]
public float LastJoypadDefaultScale { get; set; } // 最后一次手柄默认缩放
[JsonProperty("lastJoypadFocusScale")]
public float LastJoypadFocusScale { get; set; } // 最后一次手柄焦点缩放
[JsonProperty("lastPCDefaultScale")]
public float LastPCDefaultScale { get; set; } // 最后一次PC默认缩放
[JsonProperty("lastPCFocusScale")]
public float LastPCFocusScale { get; set; } // 最后一次PC焦点缩放
[JsonProperty("lastTouchDefaultScale")]
public float LastTouchDefaultScale { get; set; } // 最后一次触摸默认缩放
[JsonProperty("lastTouchFcousScale")]
public float LastTouchFocusScale { get; set; } // 最后一次触摸焦点缩放
[JsonProperty("switchWalkRunByBtn")]
public bool SwitchWalkRunByBtn { get; set; } // 通过按钮切换行走和奔跑
[JsonProperty("skiffCameraAutoFix")]
public bool SkiffCameraAutoFix { get; set; } // 小艇摄像头自动修正
[JsonProperty("skiffCameraAutoFixInCombat")]
public bool SkiffCameraAutoFixInCombat { get; set; } // 战斗中小艇摄像头自动修正
[JsonProperty("cameraDistanceRatio")]
public float CameraDistanceRatio { get; set; } // 摄像头距离比率
[JsonProperty("wwiseVibration")]
public bool WwiseVibration { get; set; } // Wwise振动
[JsonProperty("isYInited")]
public bool IsYInited { get; set; } // Y轴是否初始化
[JsonProperty("joypadSenseIndexY")]
public int JoypadSenseIndexY { get; set; } // 手柄Y轴灵敏度索引
[JsonProperty("joypadFocusSenseIndexY")]
public int JoypadFocusSenseIndexY { get; set; } // 手柄Y轴焦点灵敏度索引
[JsonProperty("mouseSenseIndexY")]
public int MouseSenseIndexY { get; set; } // 鼠标Y轴灵敏度索引
[JsonProperty("mouseFocusSenseIndexY")]
public int MouseFocusSenseIndexY { get; set; } // 鼠标Y轴焦点灵敏度索引
[JsonProperty("touchpadSenseIndexY")]
public int TouchpadSenseIndexY { get; set; } // 触摸板Y轴灵敏度索引
[JsonProperty("touchpadFocusSenseIndexY")]
public int TouchpadFocusSenseIndexY { get; set; } // 触摸板Y轴焦点灵敏度索引
[JsonProperty("lastJoypadDefaultScaleY")]
public float LastJoypadDefaultScaleY { get; set; } // 最后一次手柄Y轴默认缩放
[JsonProperty("lastJoypadFocusScaleY")]
public float LastJoypadFocusScaleY { get; set; } // 最后一次手柄Y轴焦点缩放
[JsonProperty("lastPCDefaultScaleY")]
public float LastPCDefaultScaleY { get; set; } // 最后一次PC Y轴默认缩放
[JsonProperty("lastPCFocusScaleY")]
public float LastPCFocusScaleY { get; set; } // 最后一次PC Y轴焦点缩放
[JsonProperty("lastTouchDefaultScaleY")]
public float LastTouchDefaultScaleY { get; set; } // 最后一次触摸Y轴默认缩放
[JsonProperty("lastTouchFcousScaleY")]
public float LastTouchFocusScaleY { get; set; } // 最后一次触摸Y轴焦点缩放
public static GenshinGameInputSettings? Parse(string json)
{
return JsonConvert.DeserializeObject<GenshinGameInputSettings>(json);
}
}
@@ -0,0 +1,360 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Serialization;
using BetterGenshinImpact.Genshin.Settings;
using Microsoft.Win32;
using Newtonsoft.Json;
using JsonSerializerOptions = System.Text.Json.JsonSerializerOptions;
namespace BetterGenshinImpact.Genshin.Settings2;
public class GenshinGameSettings
{
[JsonProperty("deviceUUID")]
public string DeviceUUID { get; set; } // 设备唯一标识符
[JsonProperty("userLocalDataVersionId")]
public string UserLocalDataVersionId { get; set; } // 用户本地数据版本ID
[JsonProperty("deviceLanguageType")]
public int DeviceLanguageType { get; set; } // 设备语言类型
[JsonProperty("deviceVoiceLanguageType")]
public int DeviceVoiceLanguageType { get; set; } // 设备语音语言类型
[JsonProperty("selectedServerName")]
public string SelectedServerName { get; set; } // 选择的服务器名称
[JsonProperty("localLevelIndex")]
public int LocalLevelIndex { get; set; } // 本地等级索引
[JsonProperty("deviceID")]
public string DeviceID { get; set; } // 设备ID
[JsonProperty("targetUID")]
public string TargetUID { get; set; } // 目标用户ID
[JsonProperty("curAccountName")]
public string CurAccountName { get; set; } // 当前账户名称
[JsonProperty("uiSaveData")]
public string UiSaveData { get; set; } // UI保存数据
[JsonProperty("inputData")]
public string InputData { get; set; } // 输入设置数据
[JsonProperty("graphicsData")]
public string GraphicsData { get; set; } // 图形设置数据
[JsonProperty("globalPerfData")]
public string GlobalPerfData { get; set; } // 全局性能数据
[JsonProperty("miniMapConfig")]
public int MiniMapConfig { get; set; } // 小地图配置
[JsonProperty("enableCameraSlope")]
public bool EnableCameraSlope { get; set; } // 启用相机坡度
[JsonProperty("enableCameraCombatLock")]
public bool EnableCameraCombatLock { get; set; } // 启用相机战斗锁定
[JsonProperty("completionPkg")]
public bool CompletionPkg { get; set; } // 完成的包
[JsonProperty("completionPlayGoPkg")]
public bool CompletionPlayGoPkg { get; set; } // 完成的PlayGo包
[JsonProperty("onlyPlayWithPSPlayer")]
public bool OnlyPlayWithPSPlayer { get; set; } // 仅与PS玩家一起游戏
[JsonProperty("onlyPlayWithXboxPlayer")]
public bool OnlyPlayWithXboxPlayer { get; set; } // 仅与Xbox玩家一起游戏
[JsonProperty("needPlayGoFullPkgPatch")]
public bool NeedPlayGoFullPkgPatch { get; set; } // 需要PlayGo完整包补丁
[JsonProperty("resinNotification")]
public bool ResinNotification { get; set; } // 树脂通知
[JsonProperty("exploreNotification")]
public bool ExploreNotification { get; set; } // 探索通知
[JsonProperty("volumeGlobal")]
public int VolumeGlobal { get; set; } // 全局音量
[JsonProperty("volumeSFX")]
public int VolumeSFX { get; set; } // 音效音量
[JsonProperty("volumeMusic")]
public int VolumeMusic { get; set; } // 音乐音量
[JsonProperty("volumeVoice")]
public int VolumeVoice { get; set; } // 语音音量
[JsonProperty("audioAPI")]
public int AudioAPI { get; set; } // 音频API
[JsonProperty("audioDynamicRange")]
public int AudioDynamicRange { get; set; } // 音频动态范围
[JsonProperty("audioOutput")]
public int AudioOutput { get; set; } // 音频输出
[JsonProperty("_audioSuccessInit")]
public bool AudioSuccessInit { get; set; } // 音频成功初始化
[JsonProperty("enableAudioChangeAndroidMinimumBufferCapacity")]
public bool EnableAudioChangeAndroidMinimumBufferCapacity { get; set; } // 启用更改Android最小缓冲容量的音频
[JsonProperty("audioAndroidMiniumBufferCapacity")]
public int AudioAndroidMiniumBufferCapacity { get; set; } // Android音频最小缓冲容量
[JsonProperty("vibrationLevel")]
public int VibrationLevel { get; set; } // 震动等级
[JsonProperty("vibrationIntensity")]
public int VibrationIntensity { get; set; } // 震动强度
[JsonProperty("usingNewVibrationSetting")]
public bool UsingNewVibrationSetting { get; set; } // 使用新的震动设置
[JsonProperty("motionBlur")]
public bool MotionBlur { get; set; } // 动态模糊
[JsonProperty("gyroAiming")]
public bool GyroAiming { get; set; } // 陀螺仪瞄准
[JsonProperty("gyroHorMoveSpeedIndex")]
public int GyroHorMoveSpeedIndex { get; set; } // 陀螺仪水平移动速度索引
[JsonProperty("gyroVerMoveSpeedIndex")]
public int GyroVerMoveSpeedIndex { get; set; } // 陀螺仪垂直移动速度索引
[JsonProperty("gyroHorReverse")]
public bool GyroHorReverse { get; set; } // 陀螺仪水平反转
[JsonProperty("gyroVerReverse")]
public bool GyroVerReverse { get; set; } // 陀螺仪垂直反转
[JsonProperty("gyroRotateType")]
public int GyroRotateType { get; set; } // 陀螺仪旋转类型
[JsonProperty("gyroExcludeRightStickVerInput")]
public bool GyroExcludeRightStickVerInput { get; set; } // 陀螺仪排除右摇杆垂直输入
[JsonProperty("firstHDRSetting")]
public bool FirstHDRSetting { get; set; } // 首次HDR设置
[JsonProperty("maxLuminosity")]
public float MaxLuminosity { get; set; } // 最大亮度
[JsonProperty("uiPaperWhite")]
public float UiPaperWhite { get; set; } // UI纸白
[JsonProperty("scenePaperWhite")]
public float ScenePaperWhite { get; set; } // 场景纸白
/// <summary>
/// 2.200000047683716
/// </summary>
[JsonProperty("gammaValue")]
public string GammaValue { get; set; } // 伽马值
[JsonProperty("enableHDR")]
public bool EnableHDR { get; set; } // 启用HDR
[JsonProperty("_overrideControllerMapKeyList")]
public List<string> OverrideControllerMapKeyList { get; set; } // 覆盖控制器映射键列表
[JsonProperty("_overrideControllerMapValueList")]
public List<string> OverrideControllerMapValueList { get; set; } // 覆盖控制器映射值列表
[JsonProperty("rewiredMapMigrateRecord")]
public List<string> RewiredMapMigrateRecord { get; set; } // 重布线映射迁移记录
[JsonProperty("rewiredDisableKeyboard")]
public bool RewiredDisableKeyboard { get; set; } // 重布线禁用键盘
[JsonProperty("rewiredEnableKeyboard")]
public bool RewiredEnableKeyboard { get; set; } // 重布线启用键盘
[JsonProperty("rewiredEnableEDS")]
public bool RewiredEnableEDS { get; set; } // 重布线启用EDS
[JsonProperty("disableRewiredDelayInit")]
public bool DisableRewiredDelayInit { get; set; } // 禁用重布线延迟初始化
[JsonProperty("disableRewiredInitProtection")]
public bool DisableRewiredInitProtection { get; set; } // 禁用重布线初始化保护
[JsonProperty("disableSetJoyInfoForWebViewOnPCMobile")]
public bool DisableSetJoyInfoForWebViewOnPCMobile { get; set; } // 禁用在PC和移动设备上的WebView设置Joy信息
[JsonProperty("conflictKeyBindingElementId")]
public List<int> ConflictKeyBindingElementId { get; set; } // 冲突的按键绑定元素ID
[JsonProperty("conflictKeyBindingActionId")]
public List<int> ConflictKeyBindingActionId { get; set; } // 冲突的按键绑定动作ID
[JsonProperty("lastSeenPreDownloadTime")]
public long LastSeenPreDownloadTime { get; set; } // 上次看到的预下载时间
[JsonProperty("lastSeenSettingResourceTabScriptVersion")]
public string LastSeenSettingResourceTabScriptVersion { get; set; } // 上次看到的设置资源标签脚本版本
[JsonProperty("enableEffectAssembleInEditor")]
public bool EnableEffectAssembleInEditor { get; set; } // 启用在编辑器中组装效果
[JsonProperty("forceDisableQuestResourceManagement")]
public bool ForceDisableQuestResourceManagement { get; set; } // 强制禁用任务资源管理
[JsonProperty("needReportQuestResourceDeleteStatusFiles")]
public bool NeedReportQuestResourceDeleteStatusFiles { get; set; } // 需要报告任务资源删除状态文件
[JsonProperty("disableTeamPageBackgroundSwitch")]
public bool DisableTeamPageBackgroundSwitch { get; set; } // 禁用团队页面背景切换
[JsonProperty("disableHttpDns")]
public bool DisableHttpDns { get; set; } // 禁用HTTP DNS
[JsonProperty("mtrCached")]
public bool MtrCached { get; set; } // MTR缓存
[JsonProperty("mtrIsOpen")]
public bool MtrIsOpen { get; set; } // MTR是否开启
[JsonProperty("mtrMaxTTL")]
public int MtrMaxTTL { get; set; } // MTR最大TTL
[JsonProperty("mtrTimeOut")]
public int MtrTimeOut { get; set; } // MTR超时时间
[JsonProperty("mtrTraceCount")]
public int MtrTraceCount { get; set; } // MTR跟踪次数
[JsonProperty("mtrAbortTimeOutCount")]
public int MtrAbortTimeOutCount { get; set; } // MTR中止超时计数
[JsonProperty("mtrAutoTraceInterval")]
public int MtrAutoTraceInterval { get; set; } // MTR自动跟踪间隔
[JsonProperty("mtrTraceCDEachReason")]
public int MtrTraceCDEachReason { get; set; } // MTR每个原因的冷却时间
[JsonProperty("mtrTimeInterval")]
public int MtrTimeInterval { get; set; } // MTR时间间隔
[JsonProperty("mtrBanReasons")]
public List<string> MtrBanReasons { get; set; } // MTR禁止原因
[JsonProperty("_customDataKeyList")]
public List<string> CustomDataKeyList { get; set; } // 自定义数据键列表
[JsonProperty("_customDataValueList")]
public List<string> CustomDataValueList { get; set; } // 自定义数据值列表
[JsonProperty("_serializedCodeSwitches")]
public List<int> SerializedCodeSwitches { get; set; } // 序列化代码开关
[JsonProperty("urlCheckCached")]
public bool UrlCheckCached { get; set; } // URL检查缓存
[JsonProperty("urlCheckIsOpen")]
public bool UrlCheckIsOpen { get; set; } // URL检查是否开启
[JsonProperty("urlCheckAllIP")]
public bool UrlCheckAllIP { get; set; } // URL检查所有IP
[JsonProperty("urlCheckTimeOut")]
public int UrlCheckTimeOut { get; set; } // URL检查超时时间
[JsonProperty("urlCheckSueecssTraceCount")]
public int UrlCheckSuccessTraceCount { get; set; } // URL检查成功跟踪计数
[JsonProperty("urlCheckErrorTraceCount")]
public int UrlCheckErrorTraceCount { get; set; } // URL检查错误跟踪计数
[JsonProperty("urlCheckAbortTimeOutCount")]
public int UrlCheckAbortTimeOutCount { get; set; } // URL检查中止超时计数
[JsonProperty("urlCheckTimeInterval")]
public int UrlCheckTimeInterval { get; set; } // URL检查时间间隔
[JsonProperty("urlCheckCDEachReason")]
public int UrlCheckCDEachReason { get; set; } // URL检查每个原因的冷却时间
[JsonProperty("urlCheckBanReasons")]
public List<string> UrlCheckBanReasons { get; set; } // URL检查禁止原因
[JsonProperty("mtrUseOldWinVersion")]
public bool MtrUseOldWinVersion { get; set; } // 使用旧版Windows的MTR
[JsonProperty("greyTestDeviceUniqueId")]
public string GreyTestDeviceUniqueId { get; set; } // 灰度测试设备唯一ID
[JsonProperty("muteAudioOnAppMinimized")]
public bool MuteAudioOnAppMinimized { get; set; } // 应用最小化时静音
[JsonProperty("disableFallbackControllerType")]
public bool DisableFallbackControllerType { get; set; } // 禁用回退控制器类型
[JsonProperty("lastShowDoorProgress")]
public float LastShowDoorProgress { get; set; } // 上次显示门进度
[JsonProperty("globalPerfSettingVersion")]
public int GlobalPerfSettingVersion { get; set; } // 全局性能设置版本
public static string? GetStrFromRegistry()
{
if (GenshinRegistry.GetRegistryKey() is not { } hk)
{
return null;
}
using (hk)
{
string value_name = SearchRegistryName(hk);
if (hk.GetValue(value_name) is not byte[] rawBytes)
{
return null;
}
var str = Encoding.UTF8.GetString(rawBytes);
// Debug.WriteLine(str);
return str;
}
}
public static GenshinGameSettings? Parse(string json)
{
return JsonConvert.DeserializeObject<GenshinGameSettings>(json);
}
private static string SearchRegistryName(RegistryKey key)
{
string value_name = string.Empty;
string[] names = key.GetValueNames();
foreach (string name in names)
{
if (name.Contains("GENERAL_DATA"))
{
value_name = name;
break;
}
}
if (value_name == string.Empty)
{
throw new ArgumentException(value_name);
}
return value_name;
}
}
@@ -0,0 +1,154 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Helpers.Device;
[Serializable]
public class AllPcInfo
{
public PCInfo? WMI { get; set; }
public object? DxDiag { get; set; }
public static string GetJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(GetPcInfo());
}
public static AllPcInfo GetPcInfo()
{
var pcInfo = new AllPcInfo();
pcInfo.WMI = GetPCInfo.GetClass();
pcInfo.DxDiag = GetDxDiagInfo();
return pcInfo;
}
static object? GetDxDiagInfo()
{
try
{
var path = Global.Absolute("User\\dxdiag.txt");
if (!File.Exists(path))
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "dxdiag",
Arguments = $"/t \"{path}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
Process? process = Process.Start(psi);
process?.WaitForExit();
if (process?.ExitCode != 0)
{
Debug.WriteLine("DxDiag命令执行失败。");
TaskControl.Logger.LogDebug("DxDiag命令执行失败。" + process?.ExitCode);
return null;
}
}
// Read the input file
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
string input = File.ReadAllText(path, Encoding.GetEncoding("GB2312"));
// Parse the content
var parsed = Parse(input);
Debug.WriteLine("DxDiag命令执行成功。");
return parsed;
}
catch (Exception e)
{
Debug.WriteLine("DxDiag命令执行失败:" + e.Message);
TaskControl.Logger.LogDebug("DxDiag命令执行失败:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
}
return null;
}
public static Dictionary<string, object> Parse(string input)
{
var result = new Dictionary<string, object>();
var currentSection = "";
var currentData = new Dictionary<string, object>();
var keyCount = new Dictionary<string, int>();
string[] lines = input.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
foreach (var line in lines)
{
// Skip empty lines
if (string.IsNullOrWhiteSpace(line))
continue;
// Check if it's a section header
if (line.StartsWith("----"))
{
// Save previous section if exists
if (!string.IsNullOrEmpty(currentSection) && currentData.Count > 0)
{
result[currentSection] = currentData;
currentData = new Dictionary<string, object>();
}
// Get next line as section name
continue;
}
// If line contains only letters and spaces, it's a section name
if (Regex.IsMatch(line.Trim(), @"^[A-Za-z ]+$"))
{
currentSection = line.Trim();
continue;
}
// Parse key-value pairs
if (line.Contains(":"))
{
var colonIndex = line.IndexOf(':');
var key = line.Substring(0, colonIndex).Trim();
var value = line.Substring(colonIndex + 1).Trim();
// Add to current section data
if (!string.IsNullOrEmpty(key))
{
if (currentData.ContainsKey(key))
{
if (!keyCount.ContainsKey(key))
{
keyCount[key] = 1;
}
keyCount[key]++;
key = $"{key}_{keyCount[key]}";
}
else
{
keyCount[key] = 1;
}
currentData[key] = value;
}
}
}
// Add last section
if (!string.IsNullOrEmpty(currentSection) && currentData.Count > 0)
{
result[currentSection] = currentData;
}
return result;
}
}
@@ -0,0 +1,351 @@
using System;
using System.Collections.Generic;
using System.Management;
using Newtonsoft.Json;
namespace BetterGenshinImpact.Helpers.Device;
static class GetPCInfo
{
public static string GetJson()
{
var PCInfo = GetClass();
return JsonConvert.SerializeObject(PCInfo);
}
public static PCInfo GetClass()
{
var PCInfo = new PCInfo()
{
CPU = GetCPUs(),
主板 = Get主板s(),
内存 = Get内存s(),
打印机 = Get打印机s(),
显卡 = Get显卡s(),
磁盘 = Get磁盘s(),
系统 = Get系统s(),
网卡 = Get网卡s(),
笔记本 = new 笔记本()
{
计算机类型 = Get计算机类型(),
是否笔记本 = IsLaptop(),
是否插入电源 = IsPluggedIn()
}
};
return PCInfo;
}
public static CPU[] GetCPUs()
{
var cpus = new List<CPU>();
try
{
var mc = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
var moc = mc.Get();
foreach (ManagementObject mo in moc)
{
var cpu = new CPU
{
CPU名称 = mo["Caption"].ToString(),
CPU序列号 = mo["ProcessorID"].ToString(),
设备ID = mo["DeviceID"].ToString(),
名称 = mo["Name"].ToString(),
状态 = mo["CpuStatus"].ToString(),
CPU级别 = mo["Level"].ToString(),
主机名 = mo["SystemName"].ToString(),
处理器类型 = mo["ProcessorType"].ToString()
};
cpus.Add(cpu);
}
moc = null;
mc = null;
}
catch
{
}
return cpus.ToArray();
}
public static 主板[] Get主板s()
{
var 主板s = new List<主板>();
try
{
var mc = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
var moc = mc.Get();
foreach (ManagementObject mo in moc)
{
var 主板 = new 主板
{
主板ID = mo["SerialNumber"].ToString(),
制造商 = mo["Manufacturer"].ToString(),
型号 = mo["Product"].ToString(),
版本 = mo["Version"].ToString()
};
主板s.Add(主板);
}
moc = null;
mc = null;
}
catch
{
}
return 主板s.ToArray();
}
public static 内存[] Get内存s()
{
var 内存s = new List<内存>();
try
{
var mc = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMemory");
var moc = mc.Get();
foreach (ManagementObject mo in moc)
{
var 内存 = new 内存
{
位置 = mo["DeviceLocator"].ToString(),
内存类型 = mo["Caption"].ToString(),
型号 = mo["PartNumber"].ToString(),
容量 = long.Parse(mo["Capacity"].ToString()) / 1073741824 + "GB",
序列号 = mo["SerialNumber"].ToString(),
插槽 = mo["Tag"].ToString(),
速度 = mo["Speed"].ToString()
};
内存s.Add(内存);
}
moc = null;
mc = null;
}
catch (Exception)
{
}
return 内存s.ToArray();
}
public static 网卡[] Get网卡s()
{
var 网卡s = new List<网卡>();
try
{
var mc = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE");
var moc = mc.Get();
foreach (ManagementObject mo in moc)
{
var 网卡 = new 网卡
{
IP地址 = ((String[])mo["IPAddress"])[0],
MAC地址 = mo["MACAddress"].ToString(),
名称 = mo["Caption"].ToString()
};
网卡s.Add(网卡);
}
moc = null;
mc = null;
}
catch
{
}
return 网卡s.ToArray();
}
public static 系统[] Get系统s()
{
var 系统s = new List<系统>();
try
{
var mc = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
var moc = mc.Get();
foreach (ManagementObject mo in moc)
{
var 系统 = new 系统
{
启动设备 = mo["BootDevice"].ToString(),
安装时间 = mo["InstallDate"].ToString(),
序列号 = mo["SerialNumber"].ToString(),
系统位数 = mo["OSArchitecture"].ToString(),
系统名称 = mo["Caption"].ToString(),
系统版本 = mo["Version"].ToString(),
系统盘符 = mo["SystemDrive"].ToString(),
系统目录 = mo["SystemDirectory"].ToString(),
系统硬件位置 = mo["SystemDevice"].ToString(),
计算机名 = mo["CSName"].ToString()
};
系统s.Add(系统);
}
moc = null;
mc = null;
}
catch
{
}
return 系统s.ToArray();
}
public static 磁盘[] Get磁盘s()
{
var 磁盘s = new List<磁盘>();
try
{
var mc = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
var moc = mc.Get();
foreach (ManagementObject mo in moc)
{
var 磁盘 = new 磁盘
{
型号 = mo["Model"].ToString(),
容量 = long.Parse(mo["Size"].ToString()) / 1073741824 + "GB",
序列号 = mo["SerialNumber"].ToString(),
接口类型 = mo["InterfaceType"].ToString(),
设备ID = mo["DeviceID"].ToString(),
设备名称 = mo["Caption"].ToString()
};
磁盘s.Add(磁盘);
}
moc = null;
mc = null;
}
catch
{
}
return 磁盘s.ToArray();
}
public static 打印机[] Get打印机s()
{
var 打印机s = new List<打印机>();
try
{
var mc = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
var moc = mc.Get();
foreach (ManagementObject mo in moc)
{
var 打印机 = new 打印机
{
使用接口 = mo["PortName"].ToString(),
设备ID = mo["DeviceID"].ToString(),
设备名称 = mo["Caption"].ToString(),
驱动名称 = mo["DriverName"].ToString()
};
打印机s.Add(打印机);
}
moc = null;
mc = null;
}
catch
{
}
return 打印机s.ToArray();
}
public static 显卡[] Get显卡s()
{
var 显卡s = new List<显卡>();
try
{
var mc = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
var moc = mc.Get();
foreach (ManagementObject mo in moc)
{
var 显卡 = new 显卡
{
分辨率 = mo["VideoModeDescription"].ToString(),
显存 = long.Parse(mo["AdapterRAM"].ToString()) / 1048576 + "MB",
设备ID = mo["PNPDeviceID"].ToString(),
设备名称 = mo["Caption"].ToString()
};
显卡s.Add(显卡);
}
moc = null;
mc = null;
}
catch
{
}
return 显卡s.ToArray();
}
static List<string> Get计算机类型()
{
List<string> types = new();
// Use WMI to query the ChassisTypes
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_SystemEnclosure");
foreach (ManagementObject queryObj in searcher.Get())
{
foreach (int type in (UInt16[])queryObj["ChassisTypes"])
{
types.Add(type.ToString());
}
}
return types;
}
static bool IsLaptop()
{
// Use WMI to query the ChassisTypes
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_SystemEnclosure");
foreach (ManagementObject queryObj in searcher.Get())
{
foreach (int type in (UInt16[])queryObj["ChassisTypes"])
{
// 8 and 9 represent portable and laptop, respectively
if (type == 8 || type == 9 || type == 10 || type == 14 || type == 30)
{
return true;
}
}
}
return false;
}
static bool IsPluggedIn()
{
// Use WMI to query the power status
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Battery");
foreach (ManagementObject queryObj in searcher.Get())
{
// BatteryStatus 2 means the laptop is plugged in
if ((UInt16)queryObj["BatteryStatus"] == 2)
{
return true;
}
}
return false;
}
}
@@ -0,0 +1,51 @@
using System;
using System.Runtime.InteropServices;
namespace BetterGenshinImpact.Helpers.Device;
public class MouseSettings
{
// Import the SystemParametersInfo function from the user32.dll
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool SystemParametersInfo(
uint uiAction, uint uiParam, ref uint pvParam, uint fWinIni);
// Constants for SystemParametersInfo function
private const uint SPI_GETMOUSESPEED = 0x0070;
private const uint SPI_SETMOUSESPEED = 0x0071;
private const uint SPI_GETWHEELSCROLLLINES = 0x0068;
private const uint SPI_SETWHEELSCROLLLINES = 0x0069;
// Get the current mouse speed
public static uint GetMouseSpeed()
{
uint mouseSpeed = 0;
SystemParametersInfo(SPI_GETMOUSESPEED, 0, ref mouseSpeed, 0);
return mouseSpeed;
}
// Set the mouse speed
public static void SetMouseSpeed(uint speed)
{
if (speed < 1 || speed > 20)
{
throw new ArgumentOutOfRangeException(nameof(speed), "Mouse speed must be between 1 and 20.");
}
SystemParametersInfo(SPI_SETMOUSESPEED, speed, ref speed, 0);
}
// Get the current mouse wheel scroll lines
public static uint GetMouseWheelScrollLines()
{
uint scrollLines = 0;
SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, ref scrollLines, 0);
return scrollLines;
}
// Set the mouse wheel scroll lines
public static void SetMouseWheelScrollLines(uint lines)
{
SystemParametersInfo(SPI_SETWHEELSCROLLLINES, lines, ref lines, 0);
}
}
@@ -0,0 +1,27 @@
using System;
using System.Runtime.InteropServices;
namespace BetterGenshinImpact.Helpers.Device;
public class MouseSpeedSettings
{
// Import the SystemParametersInfo function from the user32.dll
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool SystemParametersInfo(
uint uiAction, uint uiParam, uint pvParam, uint fWinIni);
// Constants for SystemParametersInfo function
private const uint SPI_GETMOUSESPEED = 0x0070;
private const uint SPI_SETMOUSESPEED = 0x0071;
public static void SetMouseSpeed(uint speed)
{
if (speed < 1 || speed > 20)
{
throw new ArgumentOutOfRangeException(nameof(speed), "Mouse speed must be between 1 and 20.");
}
SystemParametersInfo(SPI_SETMOUSESPEED, 0, speed, 0);
}
}
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
namespace BetterGenshinImpact.Helpers.Device;
[Serializable]
public class PCInfo
{
public CPU[] CPU { get; set; }
public 主板[] 主板 { get; set; }
public 内存[] 内存 { get; set; }
public 网卡[] 网卡 { get; set; }
public 系统[] 系统 { get; set; }
public 磁盘[] 磁盘 { get; set; }
public 打印机[] 打印机 { get; set; }
public 显卡[] 显卡 { get; set; }
public 笔记本 笔记本 { get; set; }
}
public class CPU
{
public string CPU序列号 { get; set; }
public string CPU名称 { get; set; }
public string 设备ID { get; set; }
public string 名称 { get; set; }
public string 状态 { get; set; }
public string CPU级别 { get; set; }
public string 主机名 { get; set; }
public string 处理器类型 { get; set; }
}
public class 主板
{
public string 主板ID { get; set; }
public string 制造商 { get; set; }
public string 型号 { get; set; }
public string 版本 { get; set; }
}
public class 内存
{
public string 内存类型 { get; set; }
public string 速度 { get; set; }
public string 容量 { get; set; }
public string 插槽 { get; set; }
public string 位置 { get; set; }
public string 型号 { get; set; }
public string 序列号 { get; set; }
}
public class 网卡
{
public string 名称 { get; set; }
public string MAC地址 { get; set; }
public string IP地址 { get; set; }
}
public class 系统
{
public string 启动设备 { get; set; }
public string 系统名称 { get; set; }
public string 计算机名 { get; set; }
public string 系统位数 { get; set; }
public string 序列号 { get; set; }
public string 系统硬件位置 { get; set; }
public string 系统目录 { get; set; }
public string 系统盘符 { get; set; }
public string 系统版本 { get; set; }
public string 安装时间 { get; set; }
}
public class 磁盘
{
public string 设备ID { get; set; }
public string 设备名称 { get; set; }
public string 序列号 { get; set; }
public string 接口类型 { get; set; }
public string 型号 { get; set; }
public string 容量 { get; set; }
}
public class 打印机
{
public string 设备名称 { get; set; }
public string 设备ID { get; set; }
public string 驱动名称 { get; set; }
public string 使用接口 { get; set; }
}
public class 显卡
{
public string 设备名称 { get; set; }
public string 显存 { get; set; }
public string 设备ID { get; set; }
public string 分辨率 { get; set; }
}
public class 笔记本
{
/**
* 其他 (1)
未知 (2)
桌面 (3)
低配置文件桌面 (4)
披萨盒 (5)
迷你塔 (6)
塔 (7)
便携式 (8)
笔记本电脑 (9)
Notebook (10)
手持 (11)
扩展坞 (12)
一起 (13)
子笔记本 (14)
节省空间 (15)
午餐盒 (16)
主系统底盘 (17)
扩展底盘 (18)
subchassis (19)
总线扩展底盘 (20)
外设底盘 (21)
存储机箱 (22)
机架式底盘 (23)
密封外壳 PC (24)
平板电脑 (30)
可转换 (31)
可拆离 (32)
https://learn.microsoft.com/zh-cn/windows/win32/cimwin32prov/win32-systemenclosure
*/
public List<string> 计算机类型 { get; set; }
public bool 是否笔记本 { get; set; }
public bool 是否插入电源 { get; set; }
public bool 系统级触控板是否启用 { get; set; } = TouchpadSoft.Instance.QueryTouchpadStatus() == 1;
public bool 是否存在触控屏 { get; set; } = TouchpadManager.HasTouchInput();
// public bool 是否存在触控屏2 { get; set; } = TouchpadManager.HasTouchInput2();
}
@@ -0,0 +1,125 @@
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
namespace BetterGenshinImpact.Helpers.Device;
public class Resolution
{
public int autoWidth = PrimaryScreen.WorkingArea.Width;
public int autoHeight = PrimaryScreen.WorkingArea.Height;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public int dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmFormName;
public short dmLogPixels;
public short dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
// 平台调用的申明
[DllImport("user32.dll")]
public static extern int EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE devMode);
[DllImport("user32.dll")]
public static extern int ChangeDisplaySettings(ref DEVMODE devMode, int flags);
// 控制改变屏幕分辨率的常量
public const int ENUM_CURRENT_SETTINGS = -1;
public const int CDS_UPDATEREGISTRY = 0x01;
public const int CDS_TEST = 0x02;
public const int DISP_CHANGE_SUCCESSFUL = 0;
public const int DISP_CHANGE_RESTART = 1;
public const int DISP_CHANGE_FAILED = -1;
// 控制改变方向的常量定义
public const int DMDO_DEFAULT = 0;
public const int DMDO_90 = 1;
public const int DMDO_180 = 2;
public const int DMDO_270 = 3;
/// <summary>
/// 修改屏幕分辨率
/// </summary>
/// <param name="width">屏幕宽度</param>
/// <param name="height">屏幕高度</param>
public void ChangeResolution(int width, int height)
{
// 初始化 DEVMODE结构
DEVMODE devmode = new DEVMODE();
devmode.dmDeviceName = new String(new char[32]);
devmode.dmFormName = new String(new char[32]);
devmode.dmSize = (short)Marshal.SizeOf(devmode);
if (EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref devmode) != 0)
{
devmode.dmPelsWidth = width;
devmode.dmPelsHeight = height;
// 改变屏幕分辨率
int iRet = ChangeDisplaySettings(ref devmode, CDS_TEST);
if (iRet == DISP_CHANGE_FAILED)
{
System.Windows.Forms.MessageBox.Show("不能执行你的请求", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
iRet = ChangeDisplaySettings(ref devmode, CDS_UPDATEREGISTRY);
switch (iRet)
{
// 成功改变
case DISP_CHANGE_SUCCESSFUL:
{
break;
}
case DISP_CHANGE_RESTART:
{
System.Windows.Forms.MessageBox.Show("你需要重新启动电脑设置才能生效", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
break;
}
default:
{
System.Windows.Forms.MessageBox.Show($"改变屏幕分辨率失败,目标{width}x{height},错误码:{iRet}", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
break;
}
}
}
}
}
}
@@ -0,0 +1,105 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Helpers.Device;
public class StickyKeysManager
{
// 导入需要的 Windows API
[DllImport("user32.dll")]
private static extern bool SystemParametersInfo(uint uiAction, uint uiParam,
ref STICKYKEYS pvParam, uint fWinIni);
// STICKYKEYS 结构体
[StructLayout(LayoutKind.Sequential)]
private struct STICKYKEYS
{
public uint cbSize;
public uint dwFlags;
}
// 常量定义
private const uint SKF_STICKYKEYSON = 0x00000001;
// 常量定义
private const uint SPI_GETSTICKYKEYS = 0x003A;
private const uint SPI_SETSTICKYKEYS = 0x003B;
private const uint SPIF_UPDATEINIFILE = 0x01;
private const uint SPIF_SENDCHANGE = 0x02;
// 粘滞键标志
private const uint SKF_HOTKEYACTIVE = 0x00000004; // 热键是否激活
private const uint SKF_CONFIRMHOTKEY = 0x00000008; // 是否显示确认对话框
private const uint SKF_HOTKEYSOUND = 0x00000010; // 是否播放声音
private const uint SKF_INDICATOR = 0x00000020; // 是否显示图标
public static void DisableStickyKeysShortcut()
{
try
{
// 创建 STICKYKEYS 结构体
STICKYKEYS stickyKeys = new STICKYKEYS();
stickyKeys.cbSize = (uint)Marshal.SizeOf(typeof(STICKYKEYS));
// 获取当前设置
SystemParametersInfo(SPI_GETSTICKYKEYS, 0, ref stickyKeys, 0);
// 禁用粘滞键
stickyKeys.dwFlags &= ~SKF_STICKYKEYSON;
// 禁用所有提示和快捷方式相关的标志
stickyKeys.dwFlags &= ~SKF_HOTKEYACTIVE; // 禁用热键
stickyKeys.dwFlags &= ~SKF_CONFIRMHOTKEY; // 禁用确认对话框
stickyKeys.dwFlags &= ~SKF_HOTKEYSOUND; // 禁用声音提示
stickyKeys.dwFlags &= ~SKF_INDICATOR; // 禁用图标显示
// 应用新设置
SystemParametersInfo(SPI_SETSTICKYKEYS, 0, ref stickyKeys,
SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
Console.WriteLine("粘滞键快捷方式已成功禁用!");
}
catch (Exception ex)
{
Console.WriteLine($"禁用粘滞键快捷方式时出错: {ex.Message}");
}
}
public static void EnableStickyKeysShortcut()
{
try
{
// 创建 STICKYKEYS 结构体
STICKYKEYS stickyKeys = new STICKYKEYS();
stickyKeys.cbSize = (uint)Marshal.SizeOf(typeof(STICKYKEYS));
// 获取当前设置
SystemParametersInfo(SPI_GETSTICKYKEYS, 0, ref stickyKeys, 0);
// 启用粘滞键
stickyKeys.dwFlags |= SKF_STICKYKEYSON;
// 启用所有提示和快捷方式相关的标志
stickyKeys.dwFlags |= SKF_HOTKEYACTIVE; // 启用热键
stickyKeys.dwFlags |= SKF_CONFIRMHOTKEY; // 启用确认对话框
stickyKeys.dwFlags |= SKF_HOTKEYSOUND; // 启用声音提示
stickyKeys.dwFlags |= SKF_INDICATOR; // 启用图标显示
// 应用新设置
SystemParametersInfo(SPI_SETSTICKYKEYS, 0, ref stickyKeys,
SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
Console.WriteLine("粘滞键快捷方式已成功启用!");
}
catch (Exception ex)
{
Console.WriteLine($"启用粘滞键快捷方式时出错: {ex.Message}");
}
}
}
@@ -0,0 +1,118 @@
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Windows.Interop;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.Model;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Helpers.Device;
public class SysDpi : Singleton<SysDpi>
{
public string? originalDpiRate;
// 显示器编号
public string ScreenIndex { get; set; } = "1";
private bool needResetDpi = false;
public SysDpi()
{
// 获取当前WPF窗口的句柄
var windowHandle = new WindowInteropHelper(UIDispatcherHelper.MainWindow).Handle;
// 使用窗口句柄获取显示器信息
var screen = Screen.FromHandle(windowHandle);
// 获取当前显示器的编号
int screenIndex = GetScreenIndex(screen);
ScreenIndex = (screenIndex + 1).ToString();
}
public void SetDpi()
{
try
{
originalDpiRate = RunSetDpiExe($"value {ScreenIndex}");
TaskControl.Logger.LogDebug("启动时查询DPI:{Num}", originalDpiRate);
if (originalDpiRate == "100")
{
TaskControl.Logger.LogError("当前DPI已经是100,无需设置");
return;
}
RunSetDpiExe($"100 {ScreenIndex}"); // 设置DPI为100
needResetDpi = true;
}
catch (Exception e)
{
TaskControl.Logger.LogError(e, "设置DPI时出错");
}
}
public void ResetDpi()
{
try
{
if (originalDpiRate != null && needResetDpi)
{
TaskControl.Logger.LogDebug("退出时恢复DPI:{Num}", originalDpiRate);
RunSetDpiExe($"{originalDpiRate} {ScreenIndex}");
}
}
catch (Exception e)
{
TaskControl.Logger.LogError(e, "重新设置DPI时出错");
}
}
public string? RunSetDpiExe(string arguments)
{
try
{
string exePath = Global.Absolute(@"video\bin\SetDPI.exe");
// 创建一个新的进程启动信息
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
FileName = exePath,
Arguments = arguments,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
// 启动进程
using Process? process = Process.Start(processStartInfo);
// 读取输出
string? output = process?.StandardOutput.ReadToEnd();
process?.WaitForExit();
return output;
}
catch (Exception ex)
{
TaskControl.Logger.LogError(ex, $"调用 SetDPI.exe 时出错: {ex.Message}");
return null;
}
}
private int GetScreenIndex(Screen screen)
{
// 获取所有显示器的列表
var screens = Screen.AllScreens;
// 查找当前显示器在列表中的索引
for (int i = 0; i < screens.Length; i++)
{
if (screens[i].DeviceName == screen.DeviceName)
{
return i;
}
}
// 如果未找到匹配的显示器,返回-1
return -1;
}
}
@@ -0,0 +1,35 @@
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Helpers.Device;
public class SystemSettingsManager
{
// 1. 在启动后强制设置成鼠标灵敏度设置:10, 滚轮一次滚动行数:3;结束后还原
private static uint _mouseSpeed = 10;
private static uint _wheelScrollLines = 3;
public static void GetSystemSettings()
{
_mouseSpeed = EnvironmentUtil.GetMouseSpeed(); // 获取鼠标灵敏度
_wheelScrollLines = EnvironmentUtil.GetWheelScrollLines(); // 获取滚轮滚动行数
TaskControl.Logger.LogDebug("当前鼠标灵敏度:{M1}, 滚轮滚动行数 {M2}", _mouseSpeed, _wheelScrollLines);
}
public static void SetSystemSettings()
{
MouseSpeedSettings.SetMouseSpeed(10); // 设置鼠标灵敏度
MouseSettings.SetMouseWheelScrollLines(3); // 设置滚轮滚动行数
TaskControl.Logger.LogDebug("强制设置后,当前鼠标灵敏度:{M1}, 滚轮滚动行数 {M2}", EnvironmentUtil.GetMouseSpeed(), EnvironmentUtil.GetWheelScrollLines());
}
public static void RestoreSystemSettings()
{
MouseSpeedSettings.SetMouseSpeed(_mouseSpeed); // 设置鼠标灵敏度
MouseSettings.SetMouseWheelScrollLines(_wheelScrollLines); // 设置滚轮滚动行数
TaskControl.Logger.LogDebug("还原设置后,当前鼠标灵敏度:{M1}, 滚轮滚动行数 {M2}", EnvironmentUtil.GetMouseSpeed(), EnvironmentUtil.GetWheelScrollLines());
}
}
@@ -0,0 +1,130 @@
using System.Windows.Input;
namespace BetterGenshinImpact.Helpers.Device;
using System;
using System.Runtime.InteropServices;
public static class TouchpadManager
{
// 定义 DEVMODE 结构
[StructLayout(LayoutKind.Sequential)]
private struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmDeviceName;
public ushort dmSpecVersion;
public ushort dmDriverVersion;
public ushort dmSize;
public ushort dmDriverExtra;
public uint dmFields;
public int dmPositionX;
public int dmPositionY;
public uint dmDisplayOrientation;
public uint dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmFormName;
public ushort dmLogPixels;
public uint dmBitsPerPel;
public uint dmPelsWidth;
public uint dmPelsHeight;
public uint dmDisplayFlags;
public uint dmDisplayFrequency;
public uint dmICMMethod;
public uint dmICMIntent;
public uint dmMediaType;
public uint dmDitherType;
public uint dmReserved1;
public uint dmReserved2;
public uint dmPanningWidth;
public uint dmPanningHeight;
}
// 导入 ChangeDisplaySettingsEx 函数
[DllImport("user32.dll", CharSet = CharSet.Ansi)]
private static extern int ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, uint dwflags, IntPtr lParam);
private const int DMDO_DEFAULT = 0;
private const int DMDO_90 = 1;
private const int DMDO_180 = 2;
private const int DMDO_270 = 3;
private const int CDS_UPDATEREGISTRY = 0x01;
private const int CDS_TEST = 0x02;
private const int CDS_FULLSCREEN = 0x04;
private const int CDS_GLOBAL = 0x08;
private const int CDS_SET_PRIMARY = 0x10;
private const int CDS_VIDEOPARAMETERS = 0x20;
private const int CDS_ENABLE_UNSAFE_MODES = 0x100;
private const int CDS_DISABLE_UNSAFE_MODES = 0x200;
private const int CDS_RESET = 0x40000000;
private const int CDS_NORESET = 0x10000000;
public static void DisableTouchpad()
{
DEVMODE devMode = new DEVMODE();
devMode.dmSize = (ushort)Marshal.SizeOf(typeof(DEVMODE));
devMode.dmFields = 0x00080000; // DM_DISPLAYORIENTATION
devMode.dmDisplayOrientation = DMDO_180; // 旋转显示方向
int result = ChangeDisplaySettingsEx(null, ref devMode, IntPtr.Zero, CDS_UPDATEREGISTRY, IntPtr.Zero);
if (result == 0)
{
Console.WriteLine("触控板已禁用。");
}
else
{
Console.WriteLine("无法禁用触控板,错误代码: " + result);
}
}
[DllImport("user32.dll")]
public static extern IntPtr GetSystemMetrics(Int32 nIndex);
const int SM_DIGITIZER = 94;
const int NID_INTEGRATED_TOUCH = 0x01;
const int NID_EXTERNAL_TOUCH = 0x02;
const int NID_INTEGRATED_PEN = 0x04;
const int NID_EXTERNAL_PEN = 0x08;
const int NID_MULTI_INPUT = 0x40;
const int NID_READY = 0x80;
public static bool IsTouchpadPresent()
{
IntPtr digitizerStatus = GetSystemMetrics(SM_DIGITIZER);
return (digitizerStatus.ToInt32() & NID_INTEGRATED_TOUCH) != 0 ||
(digitizerStatus.ToInt32() & NID_EXTERNAL_TOUCH) != 0;
}
public static bool HasTouchInput()
{
bool hasTouchInput = false;
UIDispatcherHelper.Invoke(() =>
{
foreach (TabletDevice tabletDevice in Tablet.TabletDevices)
{
//Only detect if it is a touch Screen not how many touches (i.e. Single touch or Multi-touch)
if (tabletDevice.Type == TabletDeviceType.Touch)
{
hasTouchInput = true;
}
}
});
return hasTouchInput;
}
public static bool HasTouchInput2()
{
IntPtr digitizerStatus = GetSystemMetrics(SM_DIGITIZER);
return (digitizerStatus.ToInt32() & NID_READY) == 0;
}
}
@@ -0,0 +1,144 @@
using System;
using System.Runtime.InteropServices;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.Model;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Helpers.Device;
public class TouchpadSoft : Singleton<TouchpadSoft>
{
private const string TouchpadRegistryPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\PrecisionTouchPad\Status";
private const string TouchpadRegistryKey = "Enabled";
private int? previousStatus = null;
// 获取触控板状态的方法
private int GetTouchpadStatus()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(TouchpadRegistryPath, true))
{
if (key != null)
{
object value = key.GetValue(TouchpadRegistryKey);
if (value != null)
{
return (int)value;
}
else
{
// 如果键值不存在,则写入默认值1(启用触控板)
key.SetValue(TouchpadRegistryKey, 1, RegistryValueKind.DWord);
return 1;
}
}
else
{
throw new InvalidOperationException("Registry path not found.");
}
}
}
// 设置触控板状态的方法
private void SetTouchpadStatus(int status)
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(TouchpadRegistryPath, true))
{
if (key != null)
{
key.SetValue(TouchpadRegistryKey, status, RegistryValueKind.DWord);
}
else
{
throw new InvalidOperationException("Registry path not found.");
}
}
}
// 只查询触控板状态的方法
public int QueryTouchpadStatus()
{
return GetTouchpadStatus();
}
// 检查并记录触控板状态的方法
public void CheckAndRecordStatus()
{
previousStatus = GetTouchpadStatus();
Console.WriteLine("Current Touchpad Status: " + previousStatus);
}
// 关闭触控板的方法
public void DisableTouchpad()
{
SetTouchpadStatus(0);
Console.WriteLine("Touchpad has been disabled.");
}
// 还原触控板状态的方法
public void RestoreTouchpad()
{
if (previousStatus.HasValue)
{
SetTouchpadStatus(previousStatus.Value);
Console.WriteLine("Touchpad status has been restored to: " + previousStatus.Value);
}
else
{
Console.WriteLine("No previous status recorded.");
}
}
[Flags]
public enum SendMessageTimeoutFlags : uint
{
SMTO_NORMAL = 0x0,
SMTO_BLOCK = 0x1,
SMTO_ABORTIFHUNG = 0x2,
SMTO_NOTIMEOUTIFNOTHUNG = 0x8
}
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam,
SendMessageTimeoutFlags fuFlags, uint uTimeout, out UIntPtr lpdwResult);
IntPtr HWND_BROADCAST = new IntPtr(0xffff);
const uint WM_SETTINGCHANGE = 0x1A;
const int MSG_TIMEOUT = 15000;
UIntPtr RESULT;
string ENVIRONMENT = "Environment";
public void NotifySettingChange()
{
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, UIntPtr.Zero, (IntPtr)Marshal.StringToHGlobalAnsi(ENVIRONMENT), SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, MSG_TIMEOUT, out RESULT);
}
public void SwitchTouchpadByHotKey()
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_LCONTROL);
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_LWIN);
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_F24);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_F24);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_LWIN);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_LCONTROL);
}
public void DisableTouchpadWhenEnabledByHotKey()
{
if (previousStatus == 1)
{
SwitchTouchpadByHotKey();
}
}
public void RestoreTouchpadByHotKey()
{
if (previousStatus == 1)
{
SwitchTouchpadByHotKey();
}
}
}
@@ -0,0 +1,206 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using NAudio.CoreAudioApi;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Helpers;
public class EnvironmentUtil
{
public static bool IsProcessRunning(string processName)
{
// // 检测 QQ
// bool isQQRunning = IsProcessRunning("QQ"); // QQ的进程名称可能需要确认
// Console.WriteLine("QQ is " + (isQQRunning ? "running" : "not running"));
//
// // 检测微信
// bool isWeChatRunning = IsProcessRunning("WeChat"); // WeChat的进程名称可能需要确认
// Console.WriteLine("WeChat is " + (isWeChatRunning ? "running" : "not running"));
//
// // 检测飞书
// bool isFeiShuRunning = IsProcessRunning("FeiShu"); // FeiShu的进程名称可能需要确认
// Console.WriteLine("FeiShu is " + (isFeiShuRunning ? "running" : "not running"));
// 获取所有运行中的进程
Process[] processes = Process.GetProcessesByName(processName);
return processes.Length > 0;
}
public static DateTime? LastBootUpTime()
{
try
{
// 创建管理对象查询
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem");
foreach (ManagementObject queryObj in searcher.Get())
{
// 获取系统开机时间
DateTime bootTime = ManagementDateTimeConverter.ToDateTime(queryObj["LastBootUpTime"].ToString());
Debug.WriteLine("系统开机时间: " + bootTime);
return bootTime;
}
}
catch (Exception ex)
{
Debug.WriteLine("An error occurred: " + ex.Message);
}
return null;
}
public static uint GetMouseSpeed()
{
User32.SystemParametersInfo(User32.SPI.SPI_GETMOUSESPEED, out uint mouseSpeed);
return mouseSpeed;
}
// 设置鼠标速度
public static void SetMouseSpeed(uint speed)
{
User32.SystemParametersInfo(User32.SPI.SPI_SETMOUSESPEED, speed);
}
//SPI_GETWHEELSCROLLLINES
public static uint GetWheelScrollLines()
{
User32.SystemParametersInfo(User32.SPI.SPI_GETWHEELSCROLLLINES, out uint wheelScrollLines);
return wheelScrollLines;
}
// 设置鼠标滚轮滚动行数
public static void SetWheelScrollLines(uint lines)
{
User32.SystemParametersInfo(User32.SPI.SPI_SETWHEELSCROLLLINES, lines);
}
// SPI_GETMOUSETRAILS
public static uint GetMouseTrails()
{
User32.SystemParametersInfo(User32.SPI.SPI_GETMOUSETRAILS, out uint mouseTrails);
return mouseTrails;
}
// 设置鼠标拖尾
public static void SetMouseTrails(uint trails)
{
User32.SystemParametersInfo(User32.SPI.SPI_SETMOUSETRAILS, trails);
}
// SPI_GETMOUSE
/// <summary>
/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mouse_event#remarks
/// </summary>
/// <returns></returns>
public static (int, int, int) GetMouse()
{
int[] mouseParams = new int[3];
IntPtr ptr = Marshal.AllocHGlobal(sizeof(int) * mouseParams.Length);
try
{
User32.SystemParametersInfo(User32.SPI.SPI_GETMOUSE, (uint)mouseParams.Length, ptr, User32.SPIF.None);
Marshal.Copy(ptr, mouseParams, 0, mouseParams.Length);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
return (mouseParams[0], mouseParams[1], mouseParams[2]);
}
public static void PrintMouseSettings()
{
Debug.WriteLine("鼠标速度: " + GetMouseSpeed());
Debug.WriteLine("鼠标滚轮滚动行数: " + GetWheelScrollLines());
Debug.WriteLine("鼠标拖尾: " + GetMouseTrails());
var (mouseThreshold1, mouseThreshold2, mouseThreshold3) = GetMouse();
Debug.WriteLine("鼠标阈值1 Mouse Double Click Time (ms): " + mouseThreshold1);
Debug.WriteLine("鼠标阈值2 Mouse Buttons Swapped:: " + mouseThreshold2);
Debug.WriteLine("鼠标阈值3 Mouse Speed: " + mouseThreshold3);
// Debug.WriteLine("Touchpad Enabled: " + IsTouchpadEnabled());
Debug.WriteLine("当前音量: " + GetMasterVolume());
}
public static bool IsTouchpadEnabled()
{
try
{
// Create a ManagementObjectSearcher to query for touchpad devices
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PointingDevice");
foreach (ManagementObject obj in searcher.Get())
{
// Check if the device is a touchpad
if (obj["Description"].ToString().ToLower().Contains("touchpad"))
{
// Get the status of the touchpad
string status = obj["Status"].ToString();
Debug.WriteLine($"Touchpad Status: {status}");
// Check if the touchpad is enabled
if (status.Equals("OK", StringComparison.OrdinalIgnoreCase))
{
Debug.WriteLine("The touchpad is enabled.");
return true;
}
else
{
Debug.WriteLine("The touchpad is disabled.");
return false;
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"An error occurred: {ex.Message}");
}
return true;
}
public static List<(string, int)> GetCurrentSpeakerVolume()
{
int volume = 0;
var enumerator = new MMDeviceEnumerator();
//获取音频输出设备
IEnumerable<MMDevice> speakDevices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).ToArray();
List<(string, int)> devices = new();
foreach (var speakDevice in speakDevices)
{
Debug.WriteLine($"Device Friendly Name: {speakDevice.FriendlyName}");
Debug.WriteLine($"Device Volume: {speakDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100}");
volume = (int)(speakDevice.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
devices.Add((speakDevice.FriendlyName, volume));
}
return devices;
}
public static float GetMasterVolume()
{
var enumerator = new MMDeviceEnumerator();
var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
return device.AudioEndpointVolume.MasterVolumeLevelScalar;
}
public static void GetCurrentSpeakerVolume(int volume)
{
var enumerator = new MMDeviceEnumerator();
IEnumerable<MMDevice> speakDevices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).ToArray();
if (speakDevices.Count() > 0)
{
MMDevice mMDevice = speakDevices.ToList()[0];
mMDevice.AudioEndpointVolume.MasterVolumeLevelScalar = volume / 100.0f;
}
}
}
+1 -1
View File
@@ -87,7 +87,7 @@ internal static class RuntimeHelper
catch (Exception ex)
{
Debug.WriteLine(ex);
MessageBox.Error("以管理员权限启动 BetterGI 失败,非管理员权限下所有模拟操作功能均不可用!\r\n请尝试 右键 —— 以管理员身份运行 的方式启动 BetterGI");
MessageBox.Error("以管理员权限启动软件失败,非管理员权限下所有模拟操作功能均不可用!\r\n请尝试 右键 —— 以管理员身份运行 的方式启动 BetterGI");
return;
}
}
@@ -0,0 +1,552 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Diagnostics;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Model;
using Newtonsoft.Json;
using TOS;
using TOS.Error;
using TOS.Model;
using JsonSerializer = System.Text.Json.JsonSerializer;
using BetterGenshinImpact.Model.TosUpload;
using BetterGenshinImpact.Service;
namespace BetterGenshinImpact.Helpers.Upload;
public delegate void UploadProgressCallback(long uploadedBytes, long totalBytes, double percentage);
public class TosClientHelper
{
private readonly string _configPath = Global.Absolute("User/tos.json");
private TosConfig _config;
private ITosClient _client;
private readonly DbLiteService _dbService = DbLiteService.Instance;
private class TosConfig
{
public string AccessKey { get; set; }
public string SecretKey { get; set; }
public string Endpoint { get; set; } = "https://tos-cn-beijing.volces.com";
public string Region { get; set; } = "cn-beijing";
public string BucketName { get; set; } = "seed-data-vendor";
}
public TosClientHelper()
{
LoadConfig();
InitClient();
}
private void LoadConfig()
{
try
{
if (File.Exists(_configPath))
{
var jsonString = File.ReadAllText(_configPath);
_config = JsonConvert.DeserializeObject<TosConfig>(jsonString);
if (_config == null)
{
throw new Exception("Failed to deserialize TOS config");
}
}
else
{
throw new FileNotFoundException("TOS config file not found");
}
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to load TOS config: {ex.Message}");
_config = new TosConfig();
}
}
private void InitClient()
{
try
{
_client = TosClientBuilder.Builder()
.SetAk(_config.AccessKey)
.SetSk(_config.SecretKey)
.SetEndpoint(_config.Endpoint)
.SetRegion(_config.Region)
.Build();
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to initialize TOS client: {ex.Message}");
}
}
public void UploadFile(string localFileName, string? objectKey = null)
{
Debug.WriteLine($"Uploading file: {localFileName}, object key: {objectKey}");
if (string.IsNullOrEmpty(_config.AccessKey) || string.IsNullOrEmpty(_config.SecretKey))
{
Debug.WriteLine("TOS credentials not configured");
return;
}
try
{
objectKey ??= Path.GetFileName(localFileName);
// 检查是否已经上传成功
// var collection = _dbService.UserDb.GetCollection<FileUploadItem>("FileUploads");
// var existingItem = collection.FindById(objectKey);
// if (existingItem?.Status == UploadStatus.UploadSuccess.ToString())
// {
// Debug.WriteLine($"File {objectKey} already uploaded successfully");
// return;
// }
var fileUploadItem = new FileUploadItem
{
Id = localFileName,
FilePath = localFileName,
ObjectKey = objectKey,
Status = UploadStatus.Uploading.ToString()
};
_dbService.Upsert("FileUploads", fileUploadItem);
var putObjectFromFileInput = new PutObjectFromFileInput
{
Bucket = _config.BucketName,
Key = objectKey,
FilePath = localFileName
};
var putObjectFromFileOutput = _client.PutObjectFromFile(putObjectFromFileInput);
Debug.WriteLine($"Put object succeeded, request id: {putObjectFromFileOutput.RequestID}");
fileUploadItem.Status = UploadStatus.UploadSuccess.ToString();
_dbService.Upsert("FileUploads", fileUploadItem);
}
catch (TosServerException ex)
{
Debug.WriteLine($"Put object failed, request id {ex.RequestID}");
Debug.WriteLine($"Put object failed, status code {ex.StatusCode}");
Debug.WriteLine($"Put object failed, response error code {ex.Code}");
Debug.WriteLine($"Put object failed, response error message {ex.Message}");
}
catch (TosClientException ex)
{
Debug.WriteLine($"Put object failed, error message {ex.Message}");
}
catch (Exception ex)
{
Debug.WriteLine($"Put object failed, {ex.Message}");
}
}
/// <summary>
/// 分片上传文件
/// </summary>
/// <param name="localFileName">本地文件路径</param>
/// <param name="objectKey">对象存储路径,如果为空则使用文件名</param>
/// <param name="partSize">分片大小(字节),默认20MB</param>
public void UploadLargeFile(string localFileName, string? objectKey = null, long partSize = 20 * 1024 * 1024, UploadProgressCallback? progressCallback = null)
{
Debug.WriteLine($"Uploading file: {localFileName}, object key: {objectKey}");
if (string.IsNullOrEmpty(_config.AccessKey) || string.IsNullOrEmpty(_config.SecretKey))
{
Debug.WriteLine("TOS credentials not configured");
return;
}
objectKey ??= Path.GetFileName(localFileName);
string uploadID = null;
var fileUploadItem = new FileUploadItem
{
Id = localFileName,
FilePath = localFileName,
ObjectKey = objectKey,
Status = UploadStatus.Uploading.ToString()
};
// 检查是否有未完成的上传
var collection = _dbService.UserDb.GetCollection<FileUploadItem>("FileUploads");
var existingItem = collection.FindById(localFileName);
if (existingItem?.UploadId != null)
{
uploadID = existingItem.UploadId;
Debug.WriteLine($"Found existing upload ID: {uploadID}");
}
else
{
_dbService.Upsert("FileUploads", fileUploadItem);
}
try
{
var fileInfo = new FileInfo(localFileName);
var fileSize = fileInfo.Length;
var partCount = (int)Math.Ceiling((double)fileSize / partSize);
var parts = new UploadedPart[partCount];
long totalUploadedBytes = 0;
// 如果有现有的上传ID,尝试获取已上传的分片
List<UploadedPart> existingParts = null;
if (!string.IsNullOrEmpty(uploadID))
{
existingParts = ListUploadedParts(objectKey, uploadID);
if (existingParts != null)
{
// 复制已上传的分片信息并计算已上传的字节数
foreach (var part in existingParts)
{
parts[part.PartNumber - 1] = part;
totalUploadedBytes += Math.Min(partSize, fileSize - (part.PartNumber - 1) * partSize);
}
// 报告初始进度
var initialPercentage = (double)totalUploadedBytes / fileSize * 100;
progressCallback?.Invoke(totalUploadedBytes, fileSize, initialPercentage);
}
}
// 如果没有现有的上传ID或获取分片失败,创建新的上传
if (string.IsNullOrEmpty(uploadID) || existingParts == null)
{
var createMultipartUploadInput = new CreateMultipartUploadInput
{
Bucket = _config.BucketName,
Key = objectKey,
ACL = ACLType.ACLPrivate,
StorageClass = StorageClassType.StorageClassIa
};
var createMultipartUploadOutput = _client.CreateMultipartUpload(createMultipartUploadInput);
uploadID = createMultipartUploadOutput.UploadID;
Debug.WriteLine($"Created new upload ID: {uploadID}");
fileUploadItem.UploadId = uploadID;
_dbService.Upsert("FileUploads", fileUploadItem);
totalUploadedBytes = 0;
}
// 上传缺失的分片
using (var fileStream = File.Open(localFileName, FileMode.Open, FileAccess.Read))
{
for (var i = 0; i < partCount; i++)
{
if (parts[i] != null) continue; // 跳过已上传的分片
var offset = partSize * i;
fileStream.Seek(offset, SeekOrigin.Begin);
var currentPartSize = Math.Min(partSize, fileSize - offset);
var uploadPartInput = new UploadPartInput
{
Bucket = _config.BucketName,
Key = objectKey,
UploadID = uploadID,
PartNumber = i + 1,
Content = fileStream,
ContentLength = currentPartSize
};
var uploadPartOutput = _client.UploadPart(uploadPartInput);
parts[i] = new UploadedPart { PartNumber = i + 1, ETag = uploadPartOutput.ETag };
// 更新进度
totalUploadedBytes += currentPartSize;
var percentage = (double)totalUploadedBytes / fileSize * 100;
progressCallback?.Invoke(totalUploadedBytes, fileSize, percentage);
Debug.WriteLine($"UploadPart {i + 1}/{partCount} succeeded");
}
}
// 完成分片上传
var completeMultipartUploadInput = new CompleteMultipartUploadInput
{
Bucket = _config.BucketName,
Key = objectKey,
UploadID = uploadID,
Parts = parts
};
var completeMultipartUploadOutput = _client.CompleteMultipartUpload(completeMultipartUploadInput);
Debug.WriteLine($"CompleteMultipartUpload succeeded, request id: {completeMultipartUploadOutput.RequestID}");
fileUploadItem.Status = UploadStatus.UploadSuccess.ToString();
_dbService.Upsert("FileUploads", fileUploadItem);
}
catch (TosServerException ex)
{
Debug.WriteLine($"Multipart upload failed, request id: {ex.RequestID}");
Debug.WriteLine($"Status code: {ex.StatusCode}, Error code: {ex.Code}");
Debug.WriteLine($"Error message: {ex.Message}");
}
catch (TosClientException ex)
{
Debug.WriteLine($"Multipart upload failed: {ex.Message}");
}
catch (Exception ex)
{
Debug.WriteLine($"Multipart upload failed: {ex.Message}");
}
}
/// <summary>
/// 列举指定上传ID的已上传分片信息
/// </summary>
/// <param name="objectKey">对象键</param>
/// <param name="uploadID">分片上传ID</param>
/// <returns>已上传的分片列表</returns>
public List<UploadedPart> ListUploadedParts(string objectKey, string uploadID)
{
if (string.IsNullOrEmpty(_config.AccessKey) || string.IsNullOrEmpty(_config.SecretKey))
{
Debug.WriteLine("TOS credentials not configured");
return null;
}
var allParts = new List<UploadedPart>();
try
{
var truncated = true;
var marker = 0;
while (truncated)
{
var listPartsInput = new ListPartsInput
{
Bucket = _config.BucketName,
Key = objectKey,
UploadID = uploadID,
PartNumberMarker = marker
};
var listPartsOutput = _client.ListParts(listPartsInput);
truncated = listPartsOutput.IsTruncated;
marker = listPartsOutput.NextPartNumberMarker;
Debug.WriteLine($"ListParts succeeded, request id: {listPartsOutput.RequestID}");
Debug.WriteLine($"ListParts succeeded, upload id: {uploadID}");
foreach (var part in listPartsOutput.Parts)
{
Debug.WriteLine($"Part {part.PartNumber}: ETag={part.ETag}, Size={part.Size}");
allParts.Add(new UploadedPart
{
PartNumber = part.PartNumber,
ETag = part.ETag
});
}
}
return allParts;
}
catch (TosServerException ex)
{
Debug.WriteLine($"ListParts failed, request id: {ex.RequestID}");
Debug.WriteLine($"Status code: {ex.StatusCode}, Error code: {ex.Code}");
Debug.WriteLine($"Error message: {ex.Message}");
}
catch (TosClientException ex)
{
Debug.WriteLine($"ListParts failed: {ex.Message}");
}
catch (Exception ex)
{
Debug.WriteLine($"ListParts failed: {ex.Message}");
}
return null;
}
/// <summary>
/// 恢复未完成的分片上传
/// </summary>
/// <param name="objectKey">对象键</param>
/// <param name="uploadID">分片上传ID</param>
/// <param name="localFileName">本地文件路径</param>
/// <param name="partSize">分片大小</param>
public void ResumableUpload(string objectKey, string uploadID, string localFileName, long partSize = 20 * 1024 * 1024, UploadProgressCallback? progressCallback = null)
{
// 检查是否已经上传成功
// var collection = _dbService.UserDb.GetCollection<FileUploadItem>("FileUploads");
// var existingItem = collection.FindById(objectKey);
// if (existingItem?.Status == UploadStatus.UploadSuccess.ToString())
// {
// Debug.WriteLine($"File {objectKey} already uploaded successfully");
// progressCallback?.Invoke(100, 100, 100);
// return;
// }
var fileUploadItem = new FileUploadItem
{
Id = localFileName,
FilePath = localFileName,
ObjectKey = objectKey,
UploadId = uploadID,
Status = UploadStatus.Uploading.ToString()
};
_dbService.Upsert("FileUploads", fileUploadItem);
try
{
var existingParts = ListUploadedParts(objectKey, uploadID);
if (existingParts == null)
{
Debug.WriteLine("Failed to get existing parts, starting new upload");
UploadLargeFile(localFileName, objectKey, partSize, progressCallback);
return;
}
var fileInfo = new FileInfo(localFileName);
var fileSize = fileInfo.Length;
var partCount = (int)Math.Ceiling((double)fileSize / partSize);
var parts = new UploadedPart[partCount];
long totalUploadedBytes = 0;
// 复制已上传的分片信息并计算已上传的字节数
foreach (var part in existingParts)
{
parts[part.PartNumber - 1] = part;
totalUploadedBytes += Math.Min(partSize, fileSize - (part.PartNumber - 1) * partSize);
}
// 报告初始进度
var initialPercentage = (int)((double)totalUploadedBytes / fileSize * 100);
progressCallback?.Invoke(totalUploadedBytes, fileSize, initialPercentage);
// 上传缺失的分片
using (var fileStream = File.Open(localFileName, FileMode.Open, FileAccess.Read))
{
for (var i = 0; i < partCount; i++)
{
if (parts[i] != null) continue; // 跳过已上传的分片
var offset = partSize * i;
fileStream.Seek(offset, SeekOrigin.Begin);
var currentPartSize = Math.Min(partSize, fileSize - offset);
var uploadPartInput = new UploadPartInput
{
Bucket = _config.BucketName,
Key = objectKey,
UploadID = uploadID,
PartNumber = i + 1,
Content = fileStream,
ContentLength = currentPartSize
};
var uploadPartOutput = _client.UploadPart(uploadPartInput);
parts[i] = new UploadedPart { PartNumber = i + 1, ETag = uploadPartOutput.ETag };
// 更新进度
totalUploadedBytes += currentPartSize;
var percentage = (int)((double)totalUploadedBytes / fileSize * 100);
progressCallback?.Invoke(totalUploadedBytes, fileSize, percentage);
Debug.WriteLine($"UploadPart {i + 1}/{partCount} succeeded");
}
}
// 完成分片上传
var completeMultipartUploadInput = new CompleteMultipartUploadInput
{
Bucket = _config.BucketName,
Key = objectKey,
UploadID = uploadID,
Parts = parts
};
var completeMultipartUploadOutput = _client.CompleteMultipartUpload(completeMultipartUploadInput);
Debug.WriteLine($"CompleteMultipartUpload succeeded, request id: {completeMultipartUploadOutput.RequestID}");
fileUploadItem.Status = UploadStatus.UploadSuccess.ToString();
_dbService.Upsert("FileUploads", fileUploadItem);
}
catch (Exception ex)
{
Debug.WriteLine($"ResumableUpload failed: {ex.Message}");
}
}
public void DeleteObject(string objectKey)
{
if (string.IsNullOrEmpty(_config.AccessKey) || string.IsNullOrEmpty(_config.SecretKey))
{
Debug.WriteLine("TOS credentials not configured");
return;
}
try
{
var deleteObjectInput = new DeleteObjectInput
{
Bucket = _config.BucketName,
Key = objectKey
};
var deleteObjectOutput = _client.DeleteObject(deleteObjectInput);
Debug.WriteLine($"DeleteObject succeeded, request id: {deleteObjectOutput.RequestID}");
}
catch (TosServerException ex)
{
Debug.WriteLine($"DeleteObject failed, request id: {ex.RequestID}");
Debug.WriteLine($"Status code: {ex.StatusCode}, Error code: {ex.Code}");
Debug.WriteLine($"Error message: {ex.Message}");
}
catch (TosClientException ex)
{
Debug.WriteLine($"DeleteObject failed: {ex.Message}");
}
catch (Exception ex)
{
Debug.WriteLine($"DeleteObject failed: {ex.Message}");
}
}
/// <summary>
/// 列举存储桶中的对象
/// </summary>
/// <param name="maxKeys">最大返回的对象数量,默认10个</param>
/// <returns>对象列表,如果发生错误则返回null</returns>
public ListedObject[] ListObjects(int maxKeys = 10)
{
if (string.IsNullOrEmpty(_config.AccessKey) || string.IsNullOrEmpty(_config.SecretKey))
{
Debug.WriteLine("TOS credentials not configured");
return [];
}
try
{
var listObjectsInput = new ListObjectsInput
{
Bucket = _config.BucketName,
MaxKeys = maxKeys
};
var listObjectsOutput = _client.ListObjects(listObjectsInput);
return listObjectsOutput.Contents;
}
catch (TosServerException ex)
{
Debug.WriteLine($"ListObjects failed, request id: {ex.RequestID}");
Debug.WriteLine($"Status code: {ex.StatusCode}, Error code: {ex.Code}");
Debug.WriteLine($"Error message: {ex.Message}");
}
catch (TosClientException ex)
{
Debug.WriteLine($"ListObjects failed: {ex.Message}");
}
catch (Exception ex)
{
Debug.WriteLine($"ListObjects failed: {ex.Message}");
}
return [];
}
}
+477 -1
View File
@@ -1,5 +1,23 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Helpers.Upload;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
using System.Windows;
using Newtonsoft.Json;
using LiteDB;
using BetterGenshinImpact.Model.TosUpload;
using BetterGenshinImpact.Service;
namespace BetterGenshinImpact.Model;
@@ -12,4 +30,462 @@ public partial class KeyMouseScriptItem : ObservableObject
private string _createTimeStr = string.Empty;
public DateTime CreateTime { get; set; }
}
public string Path { get; set; }
[ObservableProperty]
private bool _isUploading;
[ObservableProperty]
private double _uploadProgress;
private CancellationTokenSource? _uploadCts;
private readonly string _scriptPath = Global.Absolute(@"User\KeyMouseScript");
private readonly ILogger _logger = TaskControl.Logger;
[ObservableProperty]
private bool _isUploadSuccess;
[ObservableProperty]
private bool _isDeleting;
[ObservableProperty]
private double _deleteProgress;
[ObservableProperty]
private bool _isDeleteSuccess;
private CancellationTokenSource? _deleteCts;
[ObservableProperty]
private string _uploadSpeed = string.Empty;
private DateTime _lastProgressUpdateTime = DateTime.Now;
private long _lastUploadedSize = 0;
[ObservableProperty]
private bool _isPartiallyUploaded;
[ObservableProperty]
private string _selectedTask = "";
public List<string> TaskOptions { get; } =
[
"", "任务一", "任务二", "任务三", "任务四", "任务五",
"任务六", "任务七", "任务八", "任务九"
];
public bool CanDelete
{
get
{
if (IsUploading)
{
return false;
}
if (IsUploadSuccess || IsPartiallyUploaded)
{
return true;
}
return false;
}
}
private string FormatSpeed(double bytesPerSecond)
{
if (bytesPerSecond >= 1024 * 1024) // MB/s
{
return $"{bytesPerSecond / (1024 * 1024):F1} MB/s";
}
if (bytesPerSecond >= 1024) // KB/s
{
return $"{bytesPerSecond / 1024:F1} KB/s";
}
return $"{bytesPerSecond:F0} B/s";
}
private string GetRemotePath(string localFilePath)
{
var dirName = new DirectoryInfo(Path).Name;
var userName = TaskContext.Instance().Config.CommonConfig.UserName;
var uid = TaskContext.Instance().Config.CommonConfig.Uid;
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(uid))
{
throw new InvalidOperationException("请先设置用户名和UID");
}
if (string.IsNullOrEmpty(SelectedTask))
{
throw new InvalidOperationException("请选择本条记录的任务");
}
var relativePath = localFilePath.Replace(_scriptPath, "").TrimStart('\\');
var remotePath = $"{dirName[..10]}_{userName}_{uid}_{SelectedTask}/{relativePath}";
return remotePath.Replace(@"\", "/");
}
public void InitializeUploadStatus()
{
try
{
var collection = DbLiteService.Instance.UserDb.GetCollection<FileUploadItem>("FileUploads");
var files = Directory.GetFiles(Path, "*.*", SearchOption.AllDirectories);
var hasUploadedFiles = false;
var allFilesUploaded = true;
foreach (var file in files)
{
try
{
// var remotePath = GetRemotePath(file);
var fileUploadItem = collection.FindById(file);
// var fileUploadItem = collection.FindOne(Query.EQ("FilePath", file));
if (fileUploadItem == null)
{
allFilesUploaded = false;
continue;
}
// 取出 ObjectKey 中的 SelectedTask
// 匹配 "任务一" 到 "任务九" 的正则表达式
string pattern = @"任务[一二三四五六七八九]";
string text = "这是任务一的内容,任务二的内容...";
Match match = Regex.Match(fileUploadItem.ObjectKey, pattern);
if (match.Success)
{
SelectedTask = match.Value; // 例如: "任务一"
}
if (fileUploadItem?.Status == UploadStatus.UploadSuccess.ToString())
{
hasUploadedFiles = true;
}
else
{
allFilesUploaded = false;
}
}
catch (InvalidOperationException)
{
IsUploadSuccess = false;
IsPartiallyUploaded = false;
return;
}
}
IsUploadSuccess = allFilesUploaded;
IsPartiallyUploaded = !allFilesUploaded && hasUploadedFiles;
}
catch (Exception ex)
{
_logger.LogError(ex, "检查上传状态出错");
IsUploadSuccess = false;
IsPartiallyUploaded = false;
}
}
[RelayCommand]
private async Task Upload()
{
if (string.IsNullOrEmpty(Path) || !Directory.Exists(Path))
{
await MessageBox.ErrorAsync($"文件夹不存在:{Path}");
return;
}
try
{
// 提前验证用户信息,避免开始上传后才发现问题
_ = GetRemotePath(Path);
}
catch (InvalidOperationException e)
{
await MessageBox.ErrorAsync(e.Message);
return;
}
var hashFolder = Global.Absolute(@$"User/Common/Km/{new DirectoryInfo(Path).Name}");
// 先校验hash
if (!VerifyFileHashes(Path, hashFolder))
{
await MessageBox.ErrorAsync("上传前文件校验失败,联系管理员");
return;
}
try
{
_uploadCts = new CancellationTokenSource();
IsUploading = true;
IsUploadSuccess = false;
UploadProgress = 0;
var dirName = new DirectoryInfo(Path).Name;
_logger.LogDebug($"{dirName} 开始上传...");
await Task.Run(() =>
{
try
{
var tosClient = new TosClientHelper();
var files = Directory.GetFiles(Path, "*.*", SearchOption.AllDirectories);
// 计算所有文件的总大小
long totalSize = 0;
long uploadedSize = 0;
_lastUploadedSize = 0;
_lastProgressUpdateTime = DateTime.Now;
foreach (var file in files)
{
_uploadCts.Token.ThrowIfCancellationRequested();
totalSize += new FileInfo(file).Length;
}
foreach (var file in files)
{
_uploadCts.Token.ThrowIfCancellationRequested();
var remotePath = GetRemotePath(file);
var needUploadFileName = System.IO.Path.GetFileName(file);
var fileSize = new FileInfo(file).Length;
if (needUploadFileName == "video.mkv" || needUploadFileName == "video.mp4")
{
tosClient.UploadLargeFile(file, remotePath, 20 * 1024 * 1024, (bytes, totalBytes, percentage) =>
{
_uploadCts.Token.ThrowIfCancellationRequested();
var currentFileProgress = bytes;
var overallProgress = ((double)(uploadedSize + currentFileProgress) / totalSize) * 100;
UploadProgress = Math.Min(overallProgress, 99.9);
// 计算速度
var now = DateTime.Now;
var timeDiff = (now - _lastProgressUpdateTime).TotalSeconds;
if (timeDiff >= 0.5) // 每0.5秒更新一次速度
{
var sizeDiff = uploadedSize + currentFileProgress - _lastUploadedSize;
var speed = sizeDiff / timeDiff;
UploadSpeed = FormatSpeed(speed);
_lastProgressUpdateTime = now;
_lastUploadedSize = uploadedSize + currentFileProgress;
}
_logger.LogDebug($"上传进度: {overallProgress:F}%");
});
}
else
{
tosClient.UploadFile(file, remotePath);
}
uploadedSize += fileSize;
var progress = ((double)uploadedSize / totalSize) * 100;
UploadProgress = Math.Min(progress, 99.9);
}
UploadProgress = 100;
UploadSpeed = string.Empty; // 清空速度显示
// 上传完成后,不需要额外的文件夹状态更新
// FileUploadItem 的状态已经在 TosClientHelper 中更新
IsUploadSuccess = true;
_logger.LogDebug($"{dirName} 上传完成");
}
catch (Exception ex)
{
_logger.LogError($"上传过程中发生错误:{ex.Message}");
IsUploadSuccess = false;
throw;
}
}, _uploadCts.Token);
}
catch (OperationCanceledException)
{
_logger.LogDebug("上传已取消");
IsUploadSuccess = false;
}
catch (Exception ex)
{
_logger.LogError(ex, "上传出错");
IsUploadSuccess = false;
}
finally
{
IsUploading = false;
UploadSpeed = string.Empty; // 确保清空速度显示
if (!IsUploadSuccess)
{
UploadProgress = 0;
}
_uploadCts?.Dispose();
_uploadCts = null;
}
}
[RelayCommand]
private async Task StopUpload()
{
await _uploadCts?.CancelAsync()!;
await Task.Delay(500); // 等待上传线程结束
for (int i = 0; i < 100; i++)
{
if (!IsUploading)
{
break;
}
await Task.Delay(100);
}
// 刷新上传状态
InitializeUploadStatus();
}
[RelayCommand]
private async Task DeleteUploadedFiles()
{
try
{
// 提前验证用户信息,避免开始上传后才发现问题
_ = GetRemotePath(Path);
}
catch (InvalidOperationException e)
{
await MessageBox.ErrorAsync(e.Message);
return;
}
try
{
var dirName = new DirectoryInfo(Path).Name;
// 删除确认
var result = MessageBox.Show($"确定要清除已上传的 {dirName} 吗?", "确认清除", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result != MessageBoxResult.Yes)
{
return;
}
_deleteCts = new CancellationTokenSource();
IsDeleting = true;
IsDeleteSuccess = false;
DeleteProgress = 0;
_logger.LogDebug($"{dirName} 开始删除...");
await Task.Run(() =>
{
try
{
var tosClient = new TosClientHelper();
var files = Directory.GetFiles(Path, "*.*", SearchOption.AllDirectories);
var collection = DbLiteService.Instance.UserDb.GetCollection<FileUploadItem>("FileUploads");
foreach (var file in files)
{
_deleteCts.Token.ThrowIfCancellationRequested();
try
{
var remotePath = GetRemotePath(file);
// 删除对象存储中的文件
tosClient.DeleteObject(remotePath);
// 删除数据库中的记录
collection.Delete(file);
}
catch (Exception ex)
{
_logger.LogError($"删除文件失败:{ex.Message}");
}
}
IsDeleteSuccess = true;
// 重置上传状态
IsUploadSuccess = false;
UploadProgress = 0;
InitializeUploadStatus();
_logger.LogDebug($"{dirName} 删除完成");
}
catch (Exception ex)
{
_logger.LogError($"删除过程中发生错误:{ex.Message}");
IsDeleteSuccess = false;
throw;
}
}, _deleteCts.Token);
}
catch (OperationCanceledException)
{
_logger.LogDebug("删除已取消");
IsDeleteSuccess = false;
}
catch (Exception ex)
{
_logger.LogError(ex, "删除出错");
IsDeleteSuccess = false;
}
finally
{
IsDeleting = false;
_deleteCts?.Dispose();
_deleteCts = null;
}
}
[RelayCommand]
private void StopDelete()
{
_deleteCts?.Cancel();
}
public bool VerifyFileHashes(string pcFolder, string hashFolder)
{
var hashFilePath = System.IO.Path.Combine(hashFolder, "hash.json");
if (!File.Exists(hashFilePath))
{
// 无文件hash信息,直接返回true
_logger.LogDebug("Hash file not found");
return true;
}
var storedHashes = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(hashFilePath));
if (storedHashes == null)
{
throw new InvalidOperationException("Failed to deserialize hash file");
}
foreach (var filePath in Directory.GetFiles(pcFolder, "*.*", SearchOption.AllDirectories))
{
using (var stream = File.OpenRead(filePath))
{
if (!storedHashes.TryGetValue(System.IO.Path.GetFileName(filePath), out var storedHash))
{
Debug.WriteLine($"Hash not found for {filePath}");
continue;
}
var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(stream);
var hashString = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
if (storedHash != hashString)
{
Debug.WriteLine($"Hash mismatch for {filePath}");
return false;
}
}
}
return true;
}
}
@@ -0,0 +1,30 @@
namespace BetterGenshinImpact.Model.TosUpload;
public class FileUploadItem
{
// 与 ObjectKey 相同
public string? Id { get; set; }
// 文件路径
public string? FilePath { get; set; }
// 上传 ObjectKey
public string? ObjectKey { get; set; }
// 上传ID
public string? UploadId { get; set; }
// 上传状态
public string? Status { get; set; }
}
public enum UploadStatus
{
// 未上传
NotUpload,
// 上传中
Uploading,
// 上传成功
UploadSuccess,
}
@@ -0,0 +1,13 @@
namespace BetterGenshinImpact.Model.TosUpload;
public class FolderUploadItem
{
// 文件夹路径作为Id
public string? Id { get; set; }
// 文件夹名称
public string? FolderName { get; set; }
// 上传状态
public string? Status { get; set; }
}
@@ -0,0 +1,10 @@
namespace BetterGenshinImpact.Model.TosUpload;
public class KmItem
{
// 与 目录名 相同
public string? Id { get; set; }
// selectedTask
public string? SelectedTask { get; set; }
}
@@ -0,0 +1,29 @@
using System;
using System.Diagnostics;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Model;
using LiteDB;
namespace BetterGenshinImpact.Service;
public class DbLiteService : Singleton<DbLiteService>
{
public LiteDatabase UserDb { get; set; } = new(Global.Absolute(@"User\User.db"));
public void Upsert<T>(string collectionName, T entity) where T : new()
{
try
{
var collection = UserDb.GetCollection<T>(collectionName);
// 使用 Upsert 方法一次性处理插入或更新
collection.Upsert(entity);
Debug.WriteLine($"数据更新/插入成功");
}
catch (LiteException ex)
{
Debug.WriteLine($"数据操作失败: {ex.Message}");
throw;
}
}
}
@@ -0,0 +1,114 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Video;
using BetterGenshinImpact.Core.Video.obs;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.Genshin.Settings;
using BetterGenshinImpact.Genshin.Settings2;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Device;
using BetterGenshinImpact.Helpers.Upload;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Service.Singletons;
public class StartEndSingleton : Singleton<StartEndSingleton>
{
private Resolution? _resolution;
public void OnStartup()
{
}
public void OnMainWindowLoad()
{
TouchpadSoft.Instance.CheckAndRecordStatus();
TouchpadSoft.Instance.DisableTouchpadWhenEnabledByHotKey();
StickyKeysManager.DisableStickyKeysShortcut();
if (TaskContext.Instance().Config.CommonConfig.ChangeResolutionOnStart && !RuntimeHelper.IsDebug)
{
// 设置DPI
SysDpi.Instance.SetDpi();
Thread.Sleep(2000);
ChangeResolution();
}
// 获取PC信息
Task.Run(() =>
{
try
{
var json = AllPcInfo.GetJson();
// 保存
File.WriteAllText(Global.Absolute(@$"User/pc.json"), json);
}
catch (Exception e)
{
TaskControl.Logger.LogDebug("获取PC信息失败:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
}
});
ObsRecorder.StartObs();
var res = GameSettingsChecker.LoadGameSettingsAndCheck();
// if (res != null && res.Value == false)
// {
// // 退出
// Environment.Exit(0);
// }
// TosClientHelper.Instance.Test(Global.Absolute(@$"User/config.json"));
// var tosClient = new TosClientHelper();
// tosClient.ListObjects();
}
public void OnExit()
{
TouchpadSoft.Instance.RestoreTouchpadByHotKey();
if (TaskContext.Instance().Config.CommonConfig.RestoreResolutionOnExit && !RuntimeHelper.IsDebug)
{
ResetResolution();
Thread.Sleep(2000);
SysDpi.Instance.ResetDpi();
}
try
{
Process.GetProcessesByName("obs64").ToList().ForEach(p => p.Kill());
Process.GetProcessesByName("ffmpeg").ToList().ForEach(p => p.Kill());
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public void ChangeResolution()
{
_resolution = new Resolution();
_resolution.ChangeResolution(1920, 1080);
}
public void ResetResolution()
{
_resolution?.ChangeResolution(_resolution.autoWidth, _resolution.autoHeight);
}
}
+17 -15
View File
@@ -11,7 +11,7 @@
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:viewModel="clr-namespace:BetterGenshinImpact.ViewModel"
Title="更好的原神"
Width="900"
Width="1000"
Height="600"
d:Background="#D2D2D2"
d:DataContext="{d:DesignInstance Type=viewModel:MainWindowViewModel}"
@@ -58,7 +58,16 @@
<ui:SymbolIcon Symbol="Play24" />
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>
<ui:NavigationViewItem Content="录制回放"
NavigationCacheMode="Enabled"
TargetPageType="{x:Type pages:KeyMouseRecordPage}">
<ui:NavigationViewItem.Icon>
<ui:SymbolIcon Symbol="Record24" />
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>
<!--
<ui:NavigationViewItem Content="实时触发"
NavigationCacheMode="Enabled"
TargetPageType="{x:Type pages:TriggerSettingsPage}">
@@ -74,7 +83,7 @@
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>
<!--<ui:NavigationViewItemSeparator />-->
~1~<ui:NavigationViewItemSeparator />@1@
<ui:NavigationViewItem Content="一条龙"
NavigationCacheMode="Enabled"
@@ -90,8 +99,8 @@
</ui:NavigationViewItem.Icon>
<ui:NavigationViewItem.MenuItems>
<!--<ui:NavigationViewItemSeparator />-->
<!-- ConvertRange20 -->
~1~<ui:NavigationViewItemSeparator />@1@
~1~ ConvertRange20 @1@
<ui:NavigationViewItem Content="调度器"
NavigationCacheMode="Enabled"
TargetPageType="{x:Type pages:ScriptControlPage}">
@@ -99,7 +108,7 @@
<ui:SymbolIcon Symbol="DeveloperBoard24" />
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>
<!-- WebAsset24 | DocumentJs16 | Script16 -->
~1~ WebAsset24 | DocumentJs16 | Script16 @1@
<ui:NavigationViewItem Content="JS 脚本"
NavigationCacheMode="Enabled"
TargetPageType="{x:Type pages:JsListPage}">
@@ -107,7 +116,7 @@
<ui:SymbolIcon Symbol="DocumentJs16" />
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>
<!-- Map24 -->
~1~ Map24 @1@
<ui:NavigationViewItem Content="地图追踪"
NavigationCacheMode="Enabled"
TargetPageType="{x:Type pages:MapPathingPage}">
@@ -115,7 +124,7 @@
<ui:SymbolIcon Symbol="Map24" />
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>
<!-- Script16 -->
~1~ Script16 @1@
<ui:NavigationViewItem Content="录制回放"
NavigationCacheMode="Enabled"
TargetPageType="{x:Type pages:KeyMouseRecordPage}">
@@ -132,7 +141,7 @@
<ui:NavigationViewItem.Icon>
<ui:SymbolIcon Symbol="XboxController24" />
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>
</ui:NavigationViewItem>-->
<ui:NavigationViewItem Content="快捷键"
NavigationCacheMode="Enabled"
@@ -141,13 +150,6 @@
<ui:SymbolIcon Symbol="Flash24" />
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>
<!--<ui:NavigationViewItem Content="通知"
NavigationCacheMode="Enabled"
TargetPageType="{x:Type pages:NotificationSettingsPage}">
<ui:NavigationViewItem.Icon>
<ui:SymbolIcon Symbol="Alert24" />
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>-->
</ui:NavigationView.MenuItems>
<ui:NavigationView.FooterMenuItems>
<ui:NavigationViewItem Content="设置"
+18 -18
View File
@@ -176,26 +176,26 @@ public partial class MaskWindow : Window
}
// 读取游戏注册表配置
ReadGameSettings();
// ReadGameSettings();
}
private void ReadGameSettings()
{
try
{
SettingsContainer settings = new();
TaskContext.Instance().GameSettings = settings;
var lang = settings.Language?.TextLang;
if (lang != null && lang != TextLanguage.SimplifiedChinese)
{
_logger.LogWarning("当前游戏语言{Lang}不是简体中文,部分功能可能无法正常使用。The game language is not Simplified Chinese, some functions may not work properly", lang);
}
}
catch (Exception e)
{
_logger.LogWarning("游戏注册表配置信息读取失败:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
}
}
// private void ReadGameSettings()
// {
// try
// {
// SettingsContainer settings = new();
// TaskContext.Instance().GameSettings = settings;
// var lang = settings.Language?.TextLang;
// if (lang != null && lang != TextLanguage.SimplifiedChinese)
// {
// _logger.LogWarning("当前游戏语言{Lang}不是简体中文,部分功能可能无法正常使用。The game language is not Simplified Chinese, some functions may not work properly", lang);
// }
// }
// catch (Exception e)
// {
// _logger.LogWarning("游戏注册表配置信息读取失败:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
// }
// }
protected override void OnSourceInitialized(EventArgs e)
{
@@ -424,12 +424,119 @@
<ui:ToggleSwitch Margin="0,0,36,0" IsChecked="{Binding Config.CommonConfig.ExitToTray, Mode=TwoWay}" />
</ui:CardControl>
<ui:TextBlock Margin="0,0,0,8"
<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon Settings24}">
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="通用设置"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="通用设置"
TextWrapping="Wrap" />
</Grid>
</ui:CardExpander.Header>
<StackPanel>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="启动时修改显示器分辨率"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="1920x1080 100%"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.CommonConfig.ChangeResolutionOnStart, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="关闭时还原显示器分辨率"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="关闭时还原显示器分辨率"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.CommonConfig.RestoreResolutionOnExit, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="使用的录制工具"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="obs可以录制音频"
TextWrapping="Wrap" />
<ComboBox Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
ItemsSource="{Binding RecorderTypes, Mode=OneWay}"
SelectedItem="{Binding Config.CommonConfig.Recorder, Mode=TwoWay}">
</ComboBox>
</Grid>
</StackPanel>
</ui:CardExpander>
<!--<ui:TextBlock Margin="0,0,0,8"
FontTypography="BodyStrong"
Text="通知设置" />
Text="通知设置" />-->
<!-- Webhook -->
<ui:CardExpander Margin="0,0,0,12"
<!--<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon VirtualNetwork20}">
<ui:CardExpander.Header>
@@ -523,7 +630,7 @@
TextWrapping="Wrap" />
</Grid>
</StackPanel>
</ui:CardExpander>
</ui:CardExpander>-->
<!-- 地图 -->
<!--<ui:CardControl Margin="0,0,0,12"
+133 -107
View File
@@ -25,44 +25,6 @@
<StackPanel Margin="42,16,42,12">
<Border Height="200" CornerRadius="8">
<Grid>
<Border ClipToBounds="True" CornerRadius="8">
<Border.Background>
<ImageBrush ImageSource="pack://application:,,,/Assets/Images/banner_sayu.jpg"
RenderOptions.BitmapScalingMode="HighQuality"
Stretch="UniformToFill" />
</Border.Background>
<Border.OpacityMask>
<LinearGradientBrush StartPoint="0,1" EndPoint="1,0">
<GradientStop Color="Transparent" />
<GradientStop Offset="0.7" Color="White" />
</LinearGradientBrush>
</Border.OpacityMask>
</Border>
<Grid>
<StackPanel Margin="52,0,0,26"
HorizontalAlignment="Left"
VerticalAlignment="Bottom"
Background="Transparent">
<ui:TextBlock FontTypography="Title" Text="BetterGI" />
<ui:TextBlock FontTypography="Subtitle"
Opacity="0.8"
Text="更好的原神,免费且开源" />
<ui:TextBlock FontTypography="BodyStrong" Opacity="0.6">
<Hyperlink Command="{Binding GoToWikiUrlCommand}"
Foreground="#B7FFFFFF"
TextDecorations="None">
<Run>点击查看文档与教程</Run>
<Run FontFamily="{StaticResource FluentSystemIcons}" FontWeight="Light">&#xEE7A;</Run>
</Hyperlink>
</ui:TextBlock>
</StackPanel>
</Grid>
</Grid>
</Border>
<!-- 更好的原神,启动! -->
<ui:CardExpander Margin="0,12,0,12"
ContentPadding="0"
@@ -80,16 +42,14 @@
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="BetterGI 截图器,启动!"
Text="启动截图器"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
TextWrapping="Wrap">
截图器启动后才能使用各项功能,<Run FontWeight="Bold" TextDecorations="Underline">
点击展开启动相关配置
</Run>
。</ui:TextBlock>
截图器启动后才能使用各项功能
</ui:TextBlock>
<StackPanel Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
@@ -201,7 +161,7 @@
IsChecked="{Binding Config.WgcUseBitmapCache, Mode=TwoWay}" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<!--<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -260,7 +220,7 @@
Command="{Binding StartCaptureTestCommand}"
Content="测试图像捕获" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />-->
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -320,6 +280,61 @@
Command="{Binding OpenDisplayAdvancedGraphicsSettingsCommand}"
Content="手动设置" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="启动时检查"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="启动时检查"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.CommonConfig.ProcessCheckEnabled, Mode=TwoWay}" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="ffmpeg参数"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="ffmpeg参数"
TextWrapping="Wrap" />
<ui:TextBox Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
MinWidth="300"
MaxWidth="800"
Margin="0,0,36,0"
Text="{Binding Config.CommonConfig.FfmpegCommand, Mode=TwoWay}"
TextWrapping="Wrap" />
</Grid>
</StackPanel>
</ui:CardExpander>
@@ -399,15 +414,6 @@
TextWrapping="Wrap">
<ui:TextBlock.Inlines>
<Run Text="启动参数" />
<ui:HyperlinkButton Grid.Row="1"
Margin="0,0,0,0"
Padding="0"
Command="{Binding OpenGameCommandLineDocumentCommand}"
Cursor="Hand">
<ui:HyperlinkButton.Content>
<TextBlock FontSize="11" Text="打开文档" />
</ui:HyperlinkButton.Content>
</ui:HyperlinkButton>
</ui:TextBlock.Inlines>
</ui:TextBlock>
<ui:TextBlock Grid.Row="1"
@@ -426,63 +432,83 @@
Text="{Binding Config.GenshinStartConfig.GenshinStartArgs, Mode=TwoWay}"
TextWrapping="Wrap" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="自动进入游戏"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="原神启动后自动进入游戏(自动开门)"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.GenshinStartConfig.AutoEnterGameEnabled, Mode=TwoWay}" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="自动点击获取月卡"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="进入游戏后自动点击月卡,如果有的话"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.GenshinStartConfig.AutoClickBlessingOfTheWelkinMoonEnabled, Mode=TwoWay}" />
</Grid>
</StackPanel>
</ui:CardExpander>
<!--<ui:Button x:Name="Test" Margin="0,20,0,0" Content="测试" Command="{Binding TestCommand}" />-->
<!-- 用户信息设置 -->
<!--<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon Person24}">
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="用户信息"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="设置用户名和UID"
TextWrapping="Wrap" />
</Grid>
</ui:CardExpander.Header>
<StackPanel>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="用户名"
TextWrapping="Wrap" />
<ui:TextBox Grid.Row="0"
Grid.Column="1"
MinWidth="200"
Margin="0,0,36,0"
PlaceholderText="请输入用户名"
Text="{Binding Config.CommonConfig.UserName, Mode=TwoWay}" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="游戏内的UID"
TextWrapping="Wrap" />
<ui:TextBox Grid.Row="0"
Grid.Column="1"
MinWidth="200"
Margin="0,0,36,0"
PlaceholderText="请输入UID"
Text="{Binding Config.CommonConfig.Uid, Mode=TwoWay}" />
</Grid>
</StackPanel>
</ui:CardExpander>-->
<!--<ui:Button x:Name="Test" Margin="0,20,0,0" Content="测试" Command="{Binding TestCommand}" />-->
</StackPanel>
</Page>
@@ -7,6 +7,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:pages="clr-namespace:BetterGenshinImpact.ViewModel.Pages"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:controls="clr-namespace:BetterGenshinImpact.View.Controls"
d:DataContext="{d:DesignInstance Type=pages:KeyMouseRecordPageViewModel}"
d:DesignHeight="600"
d:DesignWidth="800"
@@ -29,28 +30,59 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0"
Margin="0,0,0,8"
FontTypography="BodyStrong"
Text="键鼠录制回放功能(实验功能)" />
<ui:TextBlock Grid.Row="1"
Margin="0,0,0,8"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
TextWrapping="Wrap">
建议在游戏内使用快捷键进行录制,录制完成后在调度器中使用。<Hyperlink Command="{Binding GoToKmScriptUrlCommand}" Foreground="{ui:ThemeResource TextFillColorSecondaryBrush}">
点击查看键鼠录制回放功能教程
</Hyperlink>
</ui:TextBlock>
<Grid Grid.Row="0" Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Row="2" Orientation="Horizontal">
<ui:TextBlock Grid.Column="0"
FontTypography="BodyStrong"
Text="键鼠录制回放功能" />
<ui:TextBlock Grid.Column="1"
Margin="12,0,0,0"
VerticalAlignment="Center"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="建议在游戏内使用快捷键进行录制" />
</Grid>
<!-- 用户信息配置 -->
<Grid Grid.Row="1" Margin="0,0,0,12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
<ColumnDefinition Width="20" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Column="0"
VerticalAlignment="Center"
Text="用户名:" />
<ui:TextBox Grid.Column="1"
PlaceholderText="请输入用户名"
Text="{Binding Config.CommonConfig.UserName, Mode=TwoWay}" />
<ui:TextBlock Grid.Column="3"
VerticalAlignment="Center"
Text="UID:" />
<ui:TextBox Grid.Column="4"
PlaceholderText="请输入UID"
Text="{Binding Config.CommonConfig.Uid, Mode=TwoWay}" />
</Grid>
<StackPanel Grid.Row="3" Orientation="Horizontal">
<ui:Button Command="{Binding OpenScriptFolderCommand}"
Content="打开脚本目录"
Content="打开目录"
Icon="{ui:SymbolIcon FolderOpen24}" />
<Separator Width="10" Opacity="0" />
<ui:Button Command="{Binding OpenLocalScriptRepoCommand}" Icon="{ui:SymbolIcon Archive24}">
<!--<ui:Button Command="{Binding OpenLocalScriptRepoCommand}" Icon="{ui:SymbolIcon Archive24}">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ui:TextBlock>脚本仓库</ui:TextBlock>
<ui:InfoBadge Margin="0,-8,-14,0"
@@ -61,7 +93,7 @@
Visibility="{Binding Config.ScriptConfig.ScriptRepoHintDotVisible, Converter={StaticResource BooleanToVisibilityConverter}}" />
</Grid>
</ui:Button>
<Separator Width="10" Opacity="0" />
<Separator Width="10" Opacity="0" />-->
<ui:Button Command="{Binding StartRecordCommand}"
Content="开始录制"
Icon="{ui:SymbolIcon Record20}"
@@ -71,24 +103,34 @@
Content="停止录制"
Icon="{ui:SymbolIcon Stop24}"
IsEnabled="{Binding IsRecording}" />
<Separator Width="20" Opacity="0" />
<ui:ToggleSwitch
Content="主界面切换识别"
IsChecked="{Binding Config.RecordConfig.PaimonSwitchEnabled, Mode=TwoWay}" />
<Separator Width="20" Opacity="0" />
<ui:ToggleSwitch
Content="使用桌面音频"
IsChecked="{Binding Config.RecordConfig.UseDesktopEnabled, Mode=TwoWay}" />
</StackPanel>
<Separator Grid.Row="3"
<Separator Grid.Row="4"
Height="10"
Opacity="0" />
<Grid Grid.Row="4">
<Grid Grid.Row="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="180" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="170" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<Grid x:Name="Col1" Grid.Column="0" />
<Grid x:Name="Col2" Grid.Column="1" />
<Grid x:Name="Col3" Grid.Column="2" />
<Grid x:Name="Col4" Grid.Column="3" />
</Grid>
<ui:ListView Grid.Row="5"
<ui:ListView Grid.Row="6"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemsSource="{Binding ScriptItems}"
@@ -101,16 +143,128 @@
<GridViewColumn Width="{Binding ElementName=Col2, Path=ActualWidth}"
DisplayMemberBinding="{Binding CreateTimeStr}"
Header="创建时间" />
<GridViewColumn Width="{Binding ElementName=Col3, Path=ActualWidth}" Header="操作">
<GridViewColumn Width="{Binding ElementName=Col3, Path=ActualWidth}" Header="任务">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding TaskOptions}"
SelectedItem="{Binding SelectedTask, Mode=TwoWay}"
Width="100">
<ComboBox.Resources>
<Style TargetType="ComboBox" BasedOn="{StaticResource DefaultComboBoxStyle}">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsUploadSuccess}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="False" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsPartiallyUploaded}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="False" />
</MultiDataTrigger>
<DataTrigger Binding="{Binding IsUploading}" Value="True">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Resources>
</ComboBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="{Binding ElementName=Col4, Path=ActualWidth}"
Header="上传操作">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<ui:Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:KeyMouseRecordPage}}, Path=DataContext.StartPlayCommand}"
CommandParameter="{Binding Name}"
Content="播放脚本"
Icon="{ui:SymbolIcon Play24}" />
</StackPanel>
<ui:Button x:Name="UploadButton"
Command="{Binding UploadCommand}"
Visibility="{Binding IsUploading, Converter={StaticResource BooleanToVisibilityRevertConverter}}">
<ui:Button.Style>
<Style TargetType="ui:Button" BasedOn="{StaticResource {x:Type ui:Button}}">
<Setter Property="Content" Value="上传" />
<Setter Property="Icon" Value="{ui:SymbolIcon CloudArrowUp24}" />
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsUploadSuccess}" Value="True">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</ui:Button.Style>
</ui:Button>
<ui:Button Command="{Binding StopUploadCommand}"
Content="停止"
Icon="{ui:SymbolIcon Stop24}"
Visibility="{Binding IsUploading, Converter={StaticResource BooleanToVisibilityConverter}}" />
<ui:Button Command="{Binding DeleteUploadedFilesCommand}"
Content="撤销上传"
Icon="{ui:SymbolIcon Delete24}"
Margin="5,0,0,0">
<ui:Button.Style>
<Style TargetType="ui:Button" BasedOn="{StaticResource {x:Type ui:Button}}">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsUploading}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="False" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsUploading}" Value="False" />
<Condition Binding="{Binding IsUploadSuccess}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="True" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsUploading}" Value="False" />
<Condition Binding="{Binding IsPartiallyUploaded}" Value="True" />
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="True" />
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsUploading}" Value="False" />
<Condition Binding="{Binding IsUploadSuccess}" Value="False" />
<Condition Binding="{Binding IsPartiallyUploaded}" Value="False" />
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="False" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
</ui:Button.Style>
</ui:Button>
<ui:TextBlock Margin="5,0,0,0"
VerticalAlignment="Center">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding IsUploadSuccess}" Value="True">
<Setter Property="Text" Value="已上传" />
<Setter Property="Foreground" Value="Green" />
</DataTrigger>
<DataTrigger Binding="{Binding IsUploading}" Value="True">
<Setter Property="Text">
<Setter.Value>
<MultiBinding StringFormat="{}{0:F1}% {1}">
<Binding Path="UploadProgress" />
<Binding Path="UploadSpeed" />
</MultiBinding>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</ui:TextBlock>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
@@ -118,9 +272,9 @@
</ListView.View>
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding EditScriptCommand}"
<!--<MenuItem Command="{Binding EditScriptCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}"
Header="修改名称" />
Header="修改名称" />-->
<MenuItem Command="{Binding DeleteScriptCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}"
Header="删除" />
@@ -0,0 +1,72 @@
<ui:FluentWindow x:Class="BetterGenshinImpact.View.Windows.UploadDialog"
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"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Width="500"
Height="400"
MinWidth="400"
MinHeight="200"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
ExtendsContentIntoTitleBar="True"
FontFamily="{DynamicResource TextThemeFontFamily}"
ResizeMode="CanMinimize"
WindowBackdropType="Mica"
WindowStartupLocation="CenterScreen"
WindowStyle="SingleBorderWindow"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TitleBar Title="上传云端" Grid.Row="0">
<ui:TitleBar.Icon>
<ui:ImageIcon Source="pack://application:,,,/Assets/Images/logo.png" />
</ui:TitleBar.Icon>
</ui:TitleBar>
<StackPanel Grid.Row="1" Margin="12">
<TextBlock Text="进度" Margin="5,5,5,2"/>
<ProgressBar x:Name="UploadProgressBar"
Margin="5"
Height="20"
Value="0"
Maximum="100"/>
<TextBlock Text="日志" Margin="5,10,5,2"/>
<ui:TextBox x:Name="LogTextBox"
Height="180"
Margin="5"
AcceptsReturn="True"
IsReadOnly="True"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"/>
<StackPanel Margin="5"
HorizontalAlignment="Right"
Orientation="Horizontal">
<ui:Button Name="BtnOk"
Margin="5"
Appearance="Primary"
Click="BtnOkClick"
Content="上传"
IsDefault="True" />
<ui:Button Name="BtnDelete"
Margin="5"
Appearance="Primary"
Click="BtnDeleteClick"
Content="删除已上传内容"
IsDefault="True" />
<ui:Button Name="BtnCancel"
Margin="5"
Click="BtnCancelClick"
Content="关闭窗口"
IsCancel="True" />
</StackPanel>
</StackPanel>
</Grid>
</ui:FluentWindow>
@@ -0,0 +1,218 @@
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Upload;
using Microsoft.Extensions.Logging;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.View.Windows;
public partial class UploadDialog
{
private readonly string scriptPath = Global.Absolute(@"User\KeyMouseScript");
private readonly string path;
private bool _isUploading;
public UploadDialog(string path)
{
InitializeComponent();
this.path = path;
this.Loaded += UploadDialogLoaded;
this.Closing += UploadDialog_Closing;
}
private void UploadDialogLoaded(object sender, RoutedEventArgs e)
{
}
private void UploadDialog_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (_isUploading)
{
e.Cancel = true;
AppendLog("正在上传中,请等待上传完成...");
}
}
private void AppendLog(string message)
{
LogTextBox.AppendText(message + "\n");
LogTextBox.ScrollToEnd();
}
private async void BtnOkClick(object sender, RoutedEventArgs e)
{
try
{
_isUploading = true;
var dirName = new DirectoryInfo(path).Name;
BtnOk.IsEnabled = false;
BtnDelete.IsEnabled = false;
BtnCancel.IsEnabled = false;
UploadProgressBar.Value = 0;
AppendLog($"{dirName} 开始上传...请不要关闭此窗口!");
var userName = TaskContext.Instance().Config.CommonConfig.UserName;
var uid = TaskContext.Instance().Config.CommonConfig.Uid;
await Task.Run(() =>
{
// 上传
try
{
var tosClient = new TosClientHelper();
// 循环 path 下的所有文件
var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
var relativePath = file.Replace(scriptPath, "").TrimStart('\\');
var needUploadFileName = Path.GetFileName(file);
var remotePath = $"{dirName[..10]}_{userName}_{uid}/{relativePath}";
remotePath = remotePath.Replace(@"\", "/");
if (needUploadFileName == "video.mkv" || needUploadFileName == "video.mp4")
{
tosClient.UploadLargeFile(file, remotePath, 20 * 1024 * 1024, (bytes, totalBytes, percentage) =>
{
UIDispatcherHelper.Invoke(() =>
{
UploadProgressBar.Value = percentage;
AppendLog($"上传进度: {percentage:F}%");
});
});
}
else
{
tosClient.UploadFile(file, remotePath);
}
}
UIDispatcherHelper.Invoke(() =>
{
UploadProgressBar.Value = 100;
AppendLog($"{dirName} 上传完成");
});
}
catch (Exception ex)
{
UIDispatcherHelper.Invoke(() =>
{
AppendLog($"上传过程中发生错误:{ex.Message}");
});
}
});
}
catch (Exception ex)
{
AppendLog($"上传出错: {ex.Message}");
TaskControl.Logger.LogDebug("上传出错" + ex.Source + "\r\n--" + Environment.NewLine + ex.StackTrace + "\r\n---" + Environment.NewLine + ex.Message);
}
finally
{
BtnOk.IsEnabled = true;
BtnDelete.IsEnabled = true;
BtnCancel.IsEnabled = true;
_isUploading = false;
}
}
private async void BtnDeleteClick(object sender, RoutedEventArgs e)
{
try
{
var dirName = new DirectoryInfo(path).Name;
var result = MessageBox.Show($"确定要删除已上传的 {dirName} 吗?", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result != MessageBoxResult.Yes)
{
return;
}
BtnOk.IsEnabled = false;
BtnDelete.IsEnabled = false;
BtnCancel.IsEnabled = false;
UploadProgressBar.Value = 0;
AppendLog($"开始删除 {dirName} ...");
var userName = TaskContext.Instance().Config.CommonConfig.UserName;
var uid = TaskContext.Instance().Config.CommonConfig.Uid;
await Task.Run(() =>
{
try
{
var tosClient = new TosClientHelper();
var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
var totalFiles = files.Length;
var currentFile = 0;
foreach (var file in files)
{
var relativePath = file.Replace(scriptPath, "").TrimStart('\\');
var remotePath = $"{dirName[..10]}_{userName}_{uid}/{relativePath}";
remotePath = remotePath.Replace(@"\", "/");
tosClient.DeleteObject(remotePath);
currentFile++;
var percentage = (double)currentFile / totalFiles * 100;
UIDispatcherHelper.Invoke(() =>
{
UploadProgressBar.Value = percentage;
AppendLog($"删除进度: {percentage:F}%");
});
}
UIDispatcherHelper.Invoke(() =>
{
UploadProgressBar.Value = 100;
AppendLog($"{dirName} 删除完成");
});
}
catch (Exception ex)
{
UIDispatcherHelper.Invoke(() =>
{
AppendLog($"删除过程中发生错误:{ex.Message}");
});
}
});
}
catch (Exception ex)
{
AppendLog($"删除出错: {ex.Message}");
TaskControl.Logger.LogDebug("删除出错" + ex.Source + "\r\n--" + Environment.NewLine + ex.StackTrace + "\r\n---" + Environment.NewLine + ex.Message);
}
finally
{
BtnOk.IsEnabled = true;
BtnDelete.IsEnabled = true;
BtnCancel.IsEnabled = true;
}
}
private void BtnCancelClick(object sender, RoutedEventArgs e)
{
if (!_isUploading)
{
Close();
}
else
{
AppendLog("正在上传中,请不要关闭窗口!");
}
}
}
@@ -14,11 +14,17 @@ using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using BetterGenshinImpact.Helpers.Device;
using BetterGenshinImpact.Service.Singletons;
using Wpf.Ui;
using Application = System.Windows.Application;
namespace BetterGenshinImpact.ViewModel;
@@ -26,7 +32,7 @@ public partial class MainWindowViewModel : ObservableObject, IViewModel
{
private readonly ILogger<MainWindowViewModel> _logger;
private readonly IConfigService _configService;
public string Title => $"BetterGI · 更好的原神 · {Global.Version}{(RuntimeHelper.IsDebug ? " · Dev" : string.Empty)}";
public string Title => $"采集版 · {Global.Version}{(RuntimeHelper.IsDebug ? " · Dev" : string.Empty)}";
[ObservableProperty]
public bool _isVisible = true;
@@ -36,6 +42,8 @@ public partial class MainWindowViewModel : ObservableObject, IViewModel
public AllConfig Config { get; set; }
private SysDpi? _sysDpi;
public MainWindowViewModel(INavigationService navigationService, IConfigService configService)
{
_configService = configService;
@@ -69,46 +77,46 @@ public partial class MainWindowViewModel : ObservableObject, IViewModel
[SuppressMessage("CommunityToolkit.Mvvm.SourceGenerators.RelayCommandGenerator", "MVVMTK0039:Async void returning method annotated with RelayCommand")]
private async void OnLoaded()
{
try
{
await Task.Run(() =>
{
try
{
var s = OcrFactory.Paddle.Ocr(new Mat(Global.Absolute(@"Assets\Model\PaddleOCR\test_ocr.png"), ImreadModes.Grayscale));
Debug.WriteLine("PaddleOcr预热结果:" + s);
}
catch (Exception e)
{
Console.WriteLine(e);
_logger.LogError("PaddleOcr预热异常,解决方案:https://bgi.huiyadan.com/faq.html:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
var innerException = e.InnerException;
if (innerException != null)
{
_logger.LogError("PaddleOcr预热内部异常,解决方案:https://bgi.huiyadan.com/faq.html:" + innerException.Source + "\r\n--" + Environment.NewLine + innerException.StackTrace + "\r\n---" + Environment.NewLine + innerException.Message);
throw innerException;
}
else
{
throw;
}
}
});
}
catch (Exception e)
{
MessageBox.Warning("PaddleOcr预热失败,解决方案:https://bgi.huiyadan.com/faq.html," + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
}
try
{
await Task.Run(GetNewestInfoAsync);
}
catch (Exception e)
{
Debug.WriteLine("获取最新版本信息失败:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
_logger.LogWarning("获取 BetterGI 最新版本信息失败");
}
// try
// {
// await Task.Run(() =>
// {
// try
// {
// var s = OcrFactory.Paddle.Ocr(new Mat(Global.Absolute(@"Assets\Model\PaddleOCR\test_ocr.png"), ImreadModes.Grayscale));
// Debug.WriteLine("PaddleOcr预热结果:" + s);
// }
// catch (Exception e)
// {
// Console.WriteLine(e);
// _logger.LogError("PaddleOcr预热异常,解决方案:https://bgi.huiyadan.com/faq.html:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
// var innerException = e.InnerException;
// if (innerException != null)
// {
// _logger.LogError("PaddleOcr预热内部异常,解决方案:https://bgi.huiyadan.com/faq.html:" + innerException.Source + "\r\n--" + Environment.NewLine + innerException.StackTrace + "\r\n---" + Environment.NewLine + innerException.Message);
// throw innerException;
// }
// else
// {
// throw;
// }
// }
// });
// }
// catch (Exception e)
// {
// MessageBox.Warning("PaddleOcr预热失败,解决方案:https://bgi.huiyadan.com/faq.html," + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
// }
//
// try
// {
// await Task.Run(GetNewestInfoAsync);
// }
// catch (Exception e)
// {
// Debug.WriteLine("获取最新版本信息失败:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
// _logger.LogWarning("获取 BetterGI 最新版本信息失败");
// }
// Win11下 BitBlt截图方式不可用,需要关闭窗口优化功能
if (OsVersionHelper.IsWindows11_OrGreater && TaskContext.Instance().Config.AutoFixWin11BitBlt)
@@ -117,9 +125,16 @@ public partial class MainWindowViewModel : ObservableObject, IViewModel
}
// 更新仓库
ScriptRepoUpdater.Instance.AutoUpdate();
// ScriptRepoUpdater.Instance.AutoUpdate();
EnvironmentUtil.PrintMouseSettings();
StartEndSingleton.Instance.OnMainWindowLoad();
}
private async Task GetNewestInfoAsync()
{
try
@@ -168,4 +183,4 @@ public partial class MainWindowViewModel : ObservableObject, IViewModel
_logger.LogWarning("获取 BetterGI 最新版本信息失败");
}
}
}
}
@@ -28,7 +28,10 @@ public partial class CommonSettingsPageViewModel : ObservableObject, INavigation
[ObservableProperty] private bool _isLoading;
[ObservableProperty] private string _webhookStatus = string.Empty;
[ObservableProperty]
private string[] _recorderTypes = ["ffmpeg", "obs"];
public CommonSettingsPageViewModel(IConfigService configService, INavigationService navigationService, NotificationService notificationService)
{
@@ -21,19 +21,25 @@ using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using Windows.System;
using BetterGenshinImpact.Helpers.Device;
using Wpf.Ui.Controls;
using Application = System.Windows.Application;
namespace BetterGenshinImpact.ViewModel.Pages;
public partial class HomePageViewModel : ObservableObject, INavigationAware, IViewModel
{
[ObservableProperty] private string[] _modeNames = GameCaptureFactory.ModeNames();
[ObservableProperty]
private string[] _modeNames = GameCaptureFactory.ModeNames();
[ObservableProperty] private string? _selectedMode = CaptureModes.BitBlt.ToString();
[ObservableProperty]
private string? _selectedMode = CaptureModes.BitBlt.ToString();
[ObservableProperty] private bool _taskDispatcherEnabled = false;
[ObservableProperty]
private bool _taskDispatcherEnabled = false;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartTriggerCommand))]
@@ -237,6 +243,7 @@ public partial class HomePageViewModel : ObservableObject, INavigationAware, IVi
_maskWindow?.Close();
_maskWindow = null;
}
TaskDispatcherEnabled = false;
_mouseKeyMonitor.Unsubscribe();
}
@@ -331,11 +338,22 @@ public partial class HomePageViewModel : ObservableObject, INavigationAware, IVi
// 检查用户是否配置了原神安装目录,如果没有,尝试从注册表中读取
if (string.IsNullOrEmpty(Config.GenshinStartConfig.InstallPath))
{
var path = GameExePath.GetWithoutCloud();
if (!string.IsNullOrEmpty(path))
Task.Run(async () =>
{
Config.GenshinStartConfig.InstallPath = path;
}
var p1 = RegistryGameLocator.GetDefaultGameInstallPath();
if (!string.IsNullOrEmpty(p1))
{
Config.GenshinStartConfig.InstallPath = p1;
}
else
{
var p2 = await UnityLogGameLocator.LocateSingleGamePathAsync();
if (!string.IsNullOrEmpty(p2))
{
Config.GenshinStartConfig.InstallPath = p2;
}
}
});
}
}
@@ -360,4 +378,4 @@ public partial class HomePageViewModel : ObservableObject, INavigationAware, IVi
win.NavigateToHtml(html);
win.ShowDialog();
}
}
}
@@ -28,6 +28,7 @@ using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Video;
using BetterGenshinImpact.GameTask.Model.Area;
using Vanara.PInvoke;
using HotKeySettingModel = BetterGenshinImpact.Model.HotKeySettingModel;
@@ -182,28 +183,28 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
);
HotKeySettingModels.Add(systemDirectory);
var timerDirectory = new HotKeySettingModel(
"实时任务"
);
HotKeySettingModels.Add(timerDirectory);
// var timerDirectory = new HotKeySettingModel(
// "实时任务"
// );
// HotKeySettingModels.Add(timerDirectory);
//
// var soloTaskDirectory = new HotKeySettingModel(
// "独立任务"
// );
// HotKeySettingModels.Add(soloTaskDirectory);
//
// var macroDirectory = new HotKeySettingModel(
// "操控辅助"
// );
// HotKeySettingModels.Add(macroDirectory);
var soloTaskDirectory = new HotKeySettingModel(
"独立任务"
);
HotKeySettingModels.Add(soloTaskDirectory);
var macroDirectory = new HotKeySettingModel(
"操控辅助"
);
HotKeySettingModels.Add(macroDirectory);
var devDirectory = new HotKeySettingModel(
/*var devDirectory = new HotKeySettingModel(
"开发者"
);
HotKeySettingModels.Add(devDirectory);
HotKeySettingModels.Add(devDirectory);*/
// 二级快捷键
systemDirectory.Children.Add(new HotKeySettingModel(
/*systemDirectory.Children.Add(new HotKeySettingModel(
"停止当前脚本/独立任务",
nameof(Config.HotKeyConfig.CancelTaskHotkey),
Config.HotKeyConfig.CancelTaskHotkey,
@@ -218,7 +219,7 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
Config.HotKeyConfig.TakeScreenshotHotkeyType,
(_, _) => { TaskTriggerDispatcher.Instance().TakeScreenshot(); }
);
systemDirectory.Children.Add(takeScreenshotHotKeySettingModel);
systemDirectory.Children.Add(takeScreenshotHotKeySettingModel);*/
systemDirectory.Children.Add(new HotKeySettingModel(
"日志与状态窗口展示开关",
@@ -233,7 +234,7 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
}
));
var autoPickEnabledHotKeySettingModel = new HotKeySettingModel(
/*var autoPickEnabledHotKeySettingModel = new HotKeySettingModel(
"自动拾取开关",
nameof(Config.HotKeyConfig.AutoPickEnabledHotkey),
Config.HotKeyConfig.AutoPickEnabledHotkey,
@@ -424,9 +425,9 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
{
OnKeyDownAction = (_, _) => { OneKeyFightTask.Instance.KeyDown(); },
OnKeyUpAction = (_, _) => { OneKeyFightTask.Instance.KeyUp(); }
});
});*/
devDirectory.Children.Add(new HotKeySettingModel(
systemDirectory.Children.Add(new HotKeySettingModel(
"启动/停止键鼠录制",
nameof(Config.HotKeyConfig.KeyMouseMacroRecordHotkey),
Config.HotKeyConfig.KeyMouseMacroRecordHotkey,
@@ -451,6 +452,7 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
}
));
/*
devDirectory.Children.Add(new HotKeySettingModel(
"(开发)获取当前大地图中心点位置",
nameof(Config.HotKeyConfig.RecBigMapPosHotkey),
@@ -499,6 +501,7 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
}
}
));
*/
// DEBUG
if (RuntimeHelper.IsDebug)
@@ -508,13 +511,13 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
);
HotKeySettingModels.Add(debugDirectory);
soloTaskDirectory.Children.Add(new HotKeySettingModel(
"启动/停止自动活动音游",
nameof(Config.HotKeyConfig.AutoMusicGameHotkey),
Config.HotKeyConfig.AutoMusicGameHotkey,
Config.HotKeyConfig.AutoMusicGameHotkeyType,
(_, _) => { SwitchSoloTask(_taskSettingsPageViewModel.SwitchAutoMusicGameCommand); }
));
// soloTaskDirectory.Children.Add(new HotKeySettingModel(
// "启动/停止自动活动音游",
// nameof(Config.HotKeyConfig.AutoMusicGameHotkey),
// Config.HotKeyConfig.AutoMusicGameHotkey,
// Config.HotKeyConfig.AutoMusicGameHotkeyType,
// (_, _) => { SwitchSoloTask(_taskSettingsPageViewModel.SwitchAutoMusicGameCommand); }
// ));
// HotKeySettingModels.Add(new HotKeySettingModel(
// "(测试)启动/停止自动追踪",
// nameof(Config.HotKeyConfig.AutoTrackHotkey),
@@ -544,6 +547,8 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
// // _taskSettingsPageViewModel.OnSwitchAutoTrackPath();
// }
// ));
// FfmpegRecorder ffmpegRecorder = new FfmpegRecorder();
debugDirectory.Children.Add(new HotKeySettingModel(
"(测试)测试",
nameof(Config.HotKeyConfig.Test1Hotkey),
@@ -575,13 +580,14 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
// 拾取物品
// Task.Run(async () => { await new ScanPickTask().Start(new CancellationToken()); });
Simulation.SendInput.Keyboard.KeyDown(false, User32.VK.VK_LMENU);
// TaskContext.Instance().PostMessageSimulator.KeyDown(User32.VK.VK_MENU);
Thread.Sleep(500);
GameCaptureRegion.GameRegion1080PPosMove(200, 100);
Thread.Sleep(500);
// TaskContext.Instance().PostMessageSimulator.KeyUp(User32.VK.VK_MENU);
Simulation.SendInput.Keyboard.KeyUp(false, User32.VK.VK_LMENU);
// ffmpegRecorder.Start();
DesktopRegion.DesktopRegionMove(0, 0);
Thread.Sleep(100);
DesktopRegion.DesktopRegionMove(500, 500);
User32.GetCursorPos(out var p);
_logger.LogInformation("当前鼠标位置:{Position}", p);
}
));
debugDirectory.Children.Add(new HotKeySettingModel(
@@ -591,8 +597,16 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
Config.HotKeyConfig.Test2HotkeyType,
(_, _) =>
{
GoToCraftingBenchTask goToCraftingBenchTask = new GoToCraftingBenchTask();
Task.Run(async () => { await goToCraftingBenchTask.Start("璃月", new CancellationToken()); });
// GoToCraftingBenchTask goToCraftingBenchTask = new GoToCraftingBenchTask();
// Task.Run(async () => { await goToCraftingBenchTask.Start("璃月", new CancellationToken()); });
// ffmpegRecorder.Stop();
DesktopRegion.DesktopRegionMove(0, 0);
Thread.Sleep(100);
Simulation.SendInput.Mouse.MoveMouseBy(500, 500);
User32.GetCursorPos(out var p);
_logger.LogInformation("当前鼠标位置:{Position}", p);
}
));
@@ -14,11 +14,24 @@ using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.Genshin.Settings2;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Device;
using BetterGenshinImpact.Helpers.Upload;
using Newtonsoft.Json;
using Wpf.Ui;
using Wpf.Ui.Controls;
using Wpf.Ui.Violeta.Controls;
using MessageBoxButton = Wpf.Ui.Controls.MessageBoxButton;
namespace BetterGenshinImpact.ViewModel.Pages;
@@ -37,6 +50,8 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
public AllConfig Config { get; set; }
string fileName = $"{DateTime.Now:yyyyMMddHH_mmssffff}";
public KeyMouseRecordPageViewModel(ISnackbarService snackbarService, IConfigService configService)
{
_snackbarService = snackbarService;
@@ -45,32 +60,57 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
private void InitScriptListViewData()
{
_scriptItems.Clear();
var fileInfos = LoadScriptFiles(scriptPath)
.OrderByDescending(f => f.CreationTime)
var directoryInfos = LoadScriptDirectories(scriptPath)
.OrderByDescending(d => d.CreationTime)
.ToList();
foreach (var f in fileInfos)
// 创建一个新的列表来存储更新后的项目
var updatedItems = new List<KeyMouseScriptItem>();
foreach (var d in directoryInfos)
{
_scriptItems.Add(new KeyMouseScriptItem
// 尝试在现有集合中查找相同路径的项目
var existingItem = _scriptItems.FirstOrDefault(item => item.Path == d.FullName);
if (existingItem != null)
{
Name = f.Name,
CreateTime = f.CreationTime,
CreateTimeStr = f.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")
});
// 如果找到现有项目,保留其状态
existingItem.InitializeUploadStatus();
updatedItems.Add(existingItem);
}
else
{
// 如果是新项目,创建新的实例
var km = new KeyMouseScriptItem
{
Name = d.Name,
Path = d.FullName,
CreateTime = d.CreationTime,
CreateTimeStr = d.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")
};
km.InitializeUploadStatus();
updatedItems.Add(km);
}
}
// 清空并重新添加项目
_scriptItems.Clear();
foreach (var item in updatedItems)
{
_scriptItems.Add(item);
}
}
private List<FileInfo> LoadScriptFiles(string folder)
private List<DirectoryInfo> LoadScriptDirectories(string folder)
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
var files = Directory.GetFiles(folder, "*.*",
SearchOption.AllDirectories);
var directories = Directory.GetDirectories(folder);
return files.Select(file => new FileInfo(file)).ToList();
return directories.Select(dir => new DirectoryInfo(dir)).ToList();
}
public void OnNavigatedTo()
@@ -85,15 +125,80 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
[RelayCommand]
public async Task OnStartRecord()
{
var s = RecordContext.Instance.SysParams; // 提前实例化,避免延迟
Debug.WriteLine(s.EnhancePointerPrecision);
if (!TaskContext.Instance().IsInitialized)
{
Toast.Warning("请先在启动页,启动截图器再使用本功能");
return;
}
if (TaskContext.Instance().Config.CommonConfig.ProcessCheckEnabled && !RuntimeHelper.IsDebug)
{
try
{
if (EnvironmentUtil.IsProcessRunning("QQ")
|| EnvironmentUtil.IsProcessRunning("WeChat")
|| EnvironmentUtil.IsProcessRunning("dingtalk")
|| EnvironmentUtil.IsProcessRunning("Feishu"))
{
throw new Exception("请关闭 QQ、微信、飞书等聊天软件再进行录制");
}
if (EnvironmentUtil.GetMasterVolume() <= 0)
{
throw new Exception("请保持系统音量大于0再进行录制");
}
}
catch (Exception e)
{
// await MessageBox.ShowAsync(e.Message, "校验错误", System.Windows.MessageBoxButton.OK, MessageBoxImage.Error);
// SystemControl.ActivateWindow(new WindowInteropHelper(UIDispatcherHelper.MainWindow).Handle);
Toast.Error(e.Message);
_logger.LogError(e.Message);
return;
}
}
fileName = $"{DateTime.Now:yyyy_MM_dd_HH_mm_ss}";
await Task.Run(() =>
{
try
{
var pcFolder = Global.Absolute(@$"User/KeyMouseScript/{fileName}");
Directory.CreateDirectory(pcFolder);
// 移动PC信息
var src = Global.Absolute(@$"User/pc.json");
if (File.Exists(src))
{
File.Copy(Global.Absolute(@$"User/pc.json"), Path.Combine(pcFolder, "pc.json"), true);
}
}
catch (Exception e)
{
TaskControl.Logger.LogDebug("移动PC信息失败:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
}
});
if (!IsRecording)
{
IsRecording = true;
await GlobalKeyMouseRecord.Instance.StartRecord();
SystemSettingsManager.GetSystemSettings();
SystemSettingsManager.SetSystemSettings();
try
{
await GlobalKeyMouseRecord.Instance.StartRecord(fileName);
}
catch (Exception e)
{
_logger.LogDebug(e, "启动录制时发生异常");
_logger.LogError(e.Message);
IsRecording = false;
}
}
}
@@ -104,9 +209,9 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
{
try
{
var macro = GlobalKeyMouseRecord.Instance.StopRecord();
GlobalKeyMouseRecord.Instance.StopRecord();
// Genshin Copilot Macro
File.WriteAllText(Path.Combine(scriptPath, $"BetterGI_GCM_{DateTime.Now:yyyyMMddHHmmssffff}.json"), macro);
// File.WriteAllText(Path.Combine(scriptPath, $"{fileName}/{fileName}.json"), macro);
// 刷新ListView
InitScriptListViewData();
IsRecording = false;
@@ -114,21 +219,87 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
catch (Exception e)
{
_logger.LogDebug(e, "停止录制时发生异常");
_logger.LogWarning(e.Message);
_logger.LogError(e.Message);
}
SystemSettingsManager.RestoreSystemSettings();
var pcFolder = Global.Absolute(@$"User/KeyMouseScript/{fileName}");
// 结束时检查游戏设置
GameSettingsChecker.LoadGameSettingsAndCheck(Path.Combine(pcFolder, "gameSettings.json"));
Task.Run(() =>
{
try
{
Directory.CreateDirectory(pcFolder);
// 移动PC信息
var src = Global.Absolute(@$"User/pc.json");
if (File.Exists(src))
{
File.Copy(Global.Absolute(@$"User/pc.json"), Path.Combine(pcFolder, "pc.json"), true);
}
}
catch (Exception e)
{
TaskControl.Logger.LogDebug("移动PC信息失败:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
}
Thread.Sleep(5000);
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
try
{
// 记录 pcFolder 目录下所有文件的 hash 信息到 hashFolder 目录下的 hash.json 文件
var hashFolder = Global.Absolute(@$"User/Common/Km/{fileName}");
Directory.CreateDirectory(hashFolder);
RecordFileHashes(pcFolder, hashFolder);
break;
}
catch (Exception e)
{
TaskControl.Logger.LogDebug("信息统计失败:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
continue;
}
}
});
}
}
[RelayCommand]
public async Task OnStartPlay(string name)
public void RecordFileHashes(string pcFolder, string hashFolder)
{
var fileHashes = new Dictionary<string, string>();
foreach (var filePath in Directory.GetFiles(pcFolder, "*.*", SearchOption.AllDirectories))
{
using (var stream = File.OpenRead(filePath))
{
var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(stream);
var hashString = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
fileHashes[Path.GetFileName(filePath)] = hashString;
}
}
var hashFilePath = Path.Combine(hashFolder, "hash.json");
Directory.CreateDirectory(hashFolder);
File.WriteAllText(hashFilePath, JsonConvert.SerializeObject(fileHashes, Formatting.Indented));
}
[RelayCommand]
public async Task OnStartPlay(string path)
{
var file = new FileInfo(Path.Combine(path, "systemInfo.json"));
var name = file.Directory?.Name;
_logger.LogInformation("重放开始:{Name}", name);
try
{
var s = await File.ReadAllTextAsync(Path.Combine(scriptPath, name));
await new TaskRunner(DispatcherTimerOperationEnum.UseSelfCaptureImage)
.RunAsync(async () => await KeyMouseMacroPlayer.PlayMacro(s, CancellationContext.Instance.Cts.Token));
.RunAsync(async () => await KeyMouseMacroPlayerJsonLine.PlayMacro(file.FullName, CancellationContext.Instance.Cts.Token));
}
catch (Exception e)
{
@@ -153,6 +324,7 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
{
return;
}
try
{
var str = PromptDialog.Prompt("请输入要修改为的名称(实际就是文件名)", "修改名称");
@@ -197,9 +369,26 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
{
return;
}
try
{
File.Delete(Path.Combine(scriptPath, item.Name));
var path = item.Path;
// 校验文件夹是否在 scriptPath 下
if (!path.StartsWith(scriptPath))
{
_snackbarService.Show(
"删除失败",
$"{path} 删除失败,不在脚本目录下",
ControlAppearance.Danger,
null,
TimeSpan.FromSeconds(3)
);
return;
}
// 删除目录
Directory.Delete(path, true);
_snackbarService.Show(
"删除成功",
$"{item.Name} 已经被删除",
@@ -236,4 +425,6 @@ public partial class KeyMouseRecordPageViewModel : ObservableObject, INavigation
Config.ScriptConfig.ScriptRepoHintDotVisible = false;
ScriptRepoUpdater.Instance.OpenLocalRepoInWebView();
}
}
}
+53
View File
@@ -0,0 +1,53 @@
cd /d %~dp0
if exist dist rd /s /q dist
mkdir dist\BetterGI
@echo [prepare compiler]
for /f "usebackq tokens=*" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property installationPath`) do set "path=%path%;%%i\MSBuild\Current\Bin;%%i\Common7\IDE"
@echo [prepare version]
cd /d ..\BetterGenshinImpact
set "script=Get-Content 'BetterGenshinImpact.csproj' | Select-String -Pattern 'AssemblyVersion\>(.*)\<\/AssemblyVersion' | ForEach-Object { $_.Matches.Groups[1].Value }"
for /f "usebackq delims=" %%i in (`powershell -NoLogo -NoProfile -Command "%script%"`) do set version=%%i
echo current version is %version%
if "%b%"=="" ( set "b=%version%" )
set "tmpfolder=%~dp0dist\BetterGI"
set "archiveFile=BetterGI_T_v%b%.7z"
set "setupFile=BetterGI_T_Setup_v%b%.exe"
echo [build app using vs2022]
cd /d %~dp0
rd /s /q ..\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64\
cd ..\
dotnet publish -c Release -p:PublishProfile=FolderProfile
echo [pack app using 7z]
cd /d %~dp0
cd /d ..\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64\
xcopy * "%tmpfolder%" /E /C /I /Y
cd /d %~dp0
del /f /q %tmpfolder%\*.lib
del /f /q %tmpfolder%\*ffmpeg*.dll
:: һЩѵ���汾����Ҫ������
del /f /q %tmpfolder%\onnxruntime*.dll
del /f /q %tmpfolder%\paddle*.dll
rd /s /q %tmpfolder%\Assets\Model
:: ����һЩ�����ļ���ʼ�����ļ����ʺϷ���Github��
if exist "E:\HuiTask\BetterGIBuild\BetterGI_train" (
xcopy "E:\HuiTask\BetterGIBuild\BetterGI_train\*" "%tmpfolder%" /E /C /I /Y
)
:: ����һЩ�����ļ�����
MicaSetup.Tools\7-Zip\7z a publish.7z %tmpfolder%\ -t7z -mx=5 -mf=BCJ2 -r -y
copy /y publish.7z .\MicaSetup\Resources\Setups\publish.7z
if exist "%zipFile%" ( del /f /q "%zipfile%" )
rename publish.7z %archiveFile%
rd /s /q dist\BetterGI
@pause
+146
View File
@@ -0,0 +1,146 @@
// This code is distributed under MIT license.
// Copyright (c) 2010-2018 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Gma.System.MouseKeyHook.Implementation;
namespace Gma.System.MouseKeyHook
{
/// <summary>
/// Used to represent a key combination as frequently used in application as shortcuts.
/// e.g. Alt+Shift+R. This combination is triggered when 'R' is pressed after 'Alt' and 'Shift' are already down.
/// </summary>
public class Combination
{
private readonly Chord _chord;
private Combination(Keys triggerKey, IEnumerable<Keys> chordKeys)
: this(triggerKey, new Chord(chordKeys))
{
}
private Combination(Keys triggerKey, Chord chord)
{
TriggerKey = triggerKey.Normalize();
_chord = chord;
}
/// <summary>
/// Last key which triggers the combination.
/// </summary>
public Keys TriggerKey { get; }
/// <summary>
/// Keys which all must be alredy down when trigger key is pressed.
/// </summary>
public IEnumerable<Keys> Chord
{
get { return _chord; }
}
/// <summary>
/// Number of chord (modifier) keys which must be already down when the trigger key is pressed.
/// </summary>
public int ChordLength
{
get { return _chord.Count; }
}
/// <summary>
/// A chainable builder method to simplify chord creation. Used along with <see cref="TriggeredBy" />,
/// <see cref="With" />, <see cref="Control" />, <see cref="Shift" />, <see cref="Alt" />.
/// </summary>
/// <param name="key"></param>
public static Combination TriggeredBy(Keys key)
{
return new Combination(key, (IEnumerable<Keys>) new Chord(Enumerable.Empty<Keys>()));
}
/// <summary>
/// A chainable builder method to simplify chord creation. Used along with <see cref="TriggeredBy" />,
/// <see cref="With" />, <see cref="Control" />, <see cref="Shift" />, <see cref="Alt" />.
/// </summary>
/// <param name="key"></param>
public Combination With(Keys key)
{
return new Combination(TriggerKey, Chord.Concat(Enumerable.Repeat(key, 1)));
}
/// <summary>
/// A chainable builder method to simplify chord creation. Used along with <see cref="TriggeredBy" />,
/// <see cref="With" />, <see cref="Control" />, <see cref="Shift" />, <see cref="Alt" />.
/// </summary>
public Combination Control()
{
return With(Keys.Control);
}
/// <summary>
/// A chainable builder method to simplify chord creation. Used along with <see cref="TriggeredBy" />,
/// <see cref="With" />, <see cref="Control" />, <see cref="Shift" />, <see cref="Alt" />.
/// </summary>
public Combination Alt()
{
return With(Keys.Alt);
}
/// <summary>
/// A chainable builder method to simplify chord creation. Used along with <see cref="TriggeredBy" />,
/// <see cref="With" />, <see cref="Control" />, <see cref="Shift" />, <see cref="Alt" />.
/// </summary>
public Combination Shift()
{
return With(Keys.Shift);
}
/// <inheritdoc />
public override string ToString()
{
return string.Join("+", Chord.Concat(Enumerable.Repeat(TriggerKey, 1)));
}
/// <summary>
/// TriggeredBy a chord from any string like this 'Alt+Shift+R'.
/// Nothe that the trigger key must be the last one.
/// </summary>
public static Combination FromString(string trigger)
{
var parts = trigger
.Split('+')
.Select(p => Enum.Parse(typeof(Keys), p))
.Cast<Keys>();
var stack = new Stack<Keys>(parts);
var triggerKey = stack.Pop();
return new Combination(triggerKey, stack);
}
/// <inheritdoc />
protected bool Equals(Combination other)
{
return
TriggerKey == other.TriggerKey
&& Chord.Equals(other.Chord);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Combination) obj);
}
/// <inheritdoc />
public override int GetHashCode()
{
return Chord.GetHashCode() ^
(int) TriggerKey;
}
}
}
+38
View File
@@ -0,0 +1,38 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using Gma.System.MouseKeyHook.Implementation;
namespace Gma.System.MouseKeyHook
{
/// <summary>
/// This is the class to start with.
/// </summary>
public static class Hook
{
/// <summary>
/// Here you find all application wide events. Both mouse and keyboard.
/// </summary>
/// <returns>
/// Returned instance is used for event subscriptions.
/// You can refetch it (you will get the same instance anyway).
/// </returns>
public static IKeyboardMouseEvents AppEvents()
{
return new AppEventFacade();
}
/// <summary>
/// Here you find all application wide events. Both mouse and keyboard.
/// </summary>
/// <returns>
/// Returned instance is used for event subscriptions.
/// You can refetch it (you will get the same instance anyway).
/// </returns>
public static IKeyboardMouseEvents GlobalEvents()
{
return new GlobalEventFacade();
}
}
}
+28
View File
@@ -0,0 +1,28 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
namespace Gma.System.MouseKeyHook.HotKeys
{
/// <summary>
/// The event arguments passed when a HotKeySet's OnHotKeysDownHold event is triggered.
/// </summary>
public sealed class HotKeyArgs : EventArgs
{
/// <summary>
/// Creates an instance of the HotKeyArgs.
/// <param name="triggeredAt">Time when the event was triggered</param>
/// </summary>
public HotKeyArgs(DateTime triggeredAt)
{
Time = triggeredAt;
}
/// <summary>
/// Time when the event was triggered
/// </summary>
public DateTime Time { get; }
}
}
+284
View File
@@ -0,0 +1,284 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Gma.System.MouseKeyHook.Implementation;
namespace Gma.System.MouseKeyHook.HotKeys
{
/// <summary>
/// An immutable set of Hot Keys that provides an event for when the set is activated.
/// </summary>
public class HotKeySet
{
/// <summary>
/// A delegate representing the signature for the OnHotKeysDownHold event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void HotKeyHandler(object sender, HotKeyArgs e);
private readonly Dictionary<Keys, bool> m_hotkeystate; //Keeps track of the status of the set of Keys
/*
* Example of m_remapping:
* a single key from the set of Keys requested is chosen to be the reference key (aka primary key)
*
* m_remapping[ Keys.LShiftKey ] = Keys.LShiftKey
* m_remapping[ Keys.RShiftKey ] = Keys.LShiftKey
*
* This allows the m_hotkeystate to use a single key (primary key) from the set that will act on behalf of all the keys in the set,
* which in turn reduces to this:
*
* Keys k = Keys.RShiftKey
* Keys primaryKey = PrimaryKeyOf( k ) = Keys.LShiftKey
* m_hotkeystate[ primaryKey ] = true/false
*/
private readonly Dictionary<Keys, Keys> m_remapping; //Used for mapping multiple keys to a single key
private bool m_enabled = true; //enabled by default
//These provide the actual status of whether a set is truly activated or not.
private int m_hotkeydowncount; //number of hot keys down
private int m_remappingCount;
//the number of remappings, i.e., a set of mappings, not the individual count in m_remapping
/// <summary>
/// Creates an instance of the HotKeySet class. Once created, the keys cannot be changed.
/// </summary>
/// <param name="hotkeys">Set of Hot Keys</param>
public HotKeySet(IEnumerable<Keys> hotkeys)
{
m_hotkeystate = new Dictionary<Keys, bool>();
m_remapping = new Dictionary<Keys, Keys>();
HotKeys = hotkeys;
InitializeKeys();
}
/// <summary>
/// Enables the ability to name the set
/// </summary>
public string Name { get; set; }
/// <summary>
/// Enables the ability to describe what the set is used for or supposed to do
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets the set of hotkeys that this class handles.
/// </summary>
public IEnumerable<Keys> HotKeys { get; }
/// <summary>
/// Returns whether the set of Keys is activated
/// </summary>
public bool HotKeysActivated
{
get { return m_hotkeydowncount == m_hotkeystate.Count - m_remappingCount; }
}
/// <summary>
/// Gets or sets the enabled state of the HotKey set.
/// </summary>
public bool Enabled
{
get { return m_enabled; }
set
{
if (value)
InitializeKeys(); //must get the actual current state of each key to update
m_enabled = value;
}
}
/// <summary>
/// Called as the user holds down the keys in the set. It is NOT triggered the first time the keys are set.
/// <see cref="OnHotKeysDownOnce" />
/// </summary>
public event HotKeyHandler OnHotKeysDownHold;
/// <summary>
/// Called whenever the hot key set is no longer active. This is essentially a KeyPress event, indicating that a full
/// key cycle has occurred, only for HotKeys because a single key removed from the set constitutes an incomplete set.
/// </summary>
public event HotKeyHandler OnHotKeysUp;
/// <summary>
/// Called the first time the down keys are set. It does not get called throughout the duration the user holds it but
/// only the
/// first time it's activated.
/// </summary>
public event HotKeyHandler OnHotKeysDownOnce;
/// <summary>
/// General invocation handler
/// </summary>
/// <param name="hotKeyDelegate"></param>
private void InvokeHotKeyHandler(HotKeyHandler hotKeyDelegate)
{
if (hotKeyDelegate != null)
hotKeyDelegate(this, new HotKeyArgs(DateTime.Now));
}
/// <summary>
/// Adds the keys into the dictionary tracking the keys and gets the real-time status of the Keys
/// from the OS
/// </summary>
private void InitializeKeys()
{
foreach (var k in HotKeys)
{
if (m_hotkeystate.ContainsKey(k))
m_hotkeystate.Add(k, false);
//assign using the current state of the keyboard
m_hotkeystate[k] = KeyboardState.GetCurrent().IsDown(k);
}
}
/// <summary>
/// Unregisters a previously set exclusive or based on the primary key.
/// </summary>
/// <param name="anyKeyInTheExclusiveOrSet">Any key used in the Registration method used to create an exclusive or set</param>
/// <returns>
/// True if successful. False doesn't indicate a failure to unregister, it indicates that the Key is not
/// registered as an Exclusive Or key or it's not the Primary Key.
/// </returns>
public bool UnregisterExclusiveOrKey(Keys anyKeyInTheExclusiveOrSet)
{
var primaryKey = GetExclusiveOrPrimaryKey(anyKeyInTheExclusiveOrSet);
if (primaryKey == Keys.None || !m_remapping.ContainsValue(primaryKey))
return false;
var keystoremove = new List<Keys>();
foreach (var pair in m_remapping)
if (pair.Value == primaryKey)
keystoremove.Add(pair.Key);
foreach (var k in keystoremove)
m_remapping.Remove(k);
--m_remappingCount;
return true;
}
/// <summary>
/// Registers a group of Keys that are already part of the HotKeySet in order to provide better flexibility among keys.
/// <example>
/// <code>
/// HotKeySet hks = new HotKeySet( new [] { Keys.T, Keys.LShiftKey, Keys.RShiftKey } );
/// RegisterExclusiveOrKey( new [] { Keys.LShiftKey, Keys.RShiftKey } );
/// </code>
/// allows either Keys.LShiftKey or Keys.RShiftKey to be combined with Keys.T.
/// </example>
/// </summary>
/// <param name="orKeySet"></param>
/// <returns>Primary key used for mapping or Keys.None on error</returns>
public Keys RegisterExclusiveOrKey(IEnumerable<Keys> orKeySet)
{
//Verification first, so as to not leave the m_remapping with a partial set.
foreach (var k in orKeySet)
if (!m_hotkeystate.ContainsKey(k))
return Keys.None;
var i = 0;
var primaryKey = Keys.None;
//Commit after verification
foreach (var k in orKeySet)
{
if (i == 0)
primaryKey = k;
m_remapping[k] = primaryKey;
++i;
}
//Must increase to keep a true count of how many keys are necessary for the activation to be true
++m_remappingCount;
return primaryKey;
}
/// <summary>
/// Gets the primary key
/// </summary>
/// <param name="k"></param>
/// <returns>The primary key if it exists, otherwise Keys.None</returns>
private Keys GetExclusiveOrPrimaryKey(Keys k)
{
return m_remapping.ContainsKey(k) ? m_remapping[k] : Keys.None;
}
/// <summary>
/// Resolves obtaining the key used for state checking.
/// </summary>
/// <param name="k"></param>
/// <returns>The primary key if it exists, otherwise the key entered</returns>
private Keys GetPrimaryKey(Keys k)
{
//If the key is remapped then get the primary keys
return m_remapping.ContainsKey(k) ? m_remapping[k] : k;
}
/// <summary>
/// </summary>
/// <param name="kex"></param>
internal void OnKey(KeyEventArgsExt kex)
{
if (!Enabled)
return;
//Gets the primary key if mapped to a single key or gets the key itself
var primaryKey = GetPrimaryKey(kex.KeyCode);
if (kex.IsKeyDown)
OnKeyDown(primaryKey);
else //reset
OnKeyUp(primaryKey);
}
private void OnKeyDown(Keys k)
{
//If the keys are activated still then keep invoking the event
if (HotKeysActivated)
{
InvokeHotKeyHandler(OnHotKeysDownHold); //Call the duration event
}
//indicates the key's state is current false but the key is now down
else if (m_hotkeystate.ContainsKey(k) && !m_hotkeystate[k])
{
m_hotkeystate[k] = true; //key's state is down
++m_hotkeydowncount; //increase the number of keys down in this set
if (HotKeysActivated) //because of the increase, check whether the set is activated
InvokeHotKeyHandler(OnHotKeysDownOnce); //Call the initial event
}
}
private void OnKeyUp(Keys k)
{
if (m_hotkeystate.ContainsKey(k) && m_hotkeystate[k]) //indicates the key's state was down but now it's up
{
var wasActive = HotKeysActivated;
m_hotkeystate[k] = false; //key's state is up
--m_hotkeydowncount; //this set is no longer ready
if (wasActive)
InvokeHotKeyHandler(OnHotKeysUp); //call the KeyUp event because the set is no longer active
}
}
}
}
@@ -0,0 +1,48 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System.Collections.Generic;
namespace Gma.System.MouseKeyHook.HotKeys
{
/// <summary>
/// A collection of HotKeySets
/// </summary>
public sealed class HotKeySetCollection : List<HotKeySet>
{
private KeyChainHandler m_keyChain;
/// <summary>
/// Adds a HotKeySet to the collection.
/// </summary>
/// <param name="hks"></param>
public new void Add(HotKeySet hks)
{
m_keyChain += hks.OnKey;
base.Add(hks);
}
/// <summary>
/// Removes the HotKeySet from the collection.
/// </summary>
/// <param name="hks"></param>
public new void Remove(HotKeySet hks)
{
m_keyChain -= hks.OnKey;
base.Remove(hks);
}
/// <summary>
/// Uses a multi-case delegate to invoke individual HotKeySets if the Key is in use by any HotKeySets.
/// </summary>
/// <param name="e"></param>
internal void OnKey(KeyEventArgsExt e)
{
if (m_keyChain != null)
m_keyChain(e);
}
private delegate void KeyChainHandler(KeyEventArgsExt kex);
}
}
@@ -0,0 +1,4 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
+85
View File
@@ -0,0 +1,85 @@
Until a separate, full-featured test version is ready, here's a quick update that can be made to the TestFormHookListeners:
//HotKeySetsListener inherits KeyboardHookListener
private readonly HotKeySetsListener m_KeyboardHookManager;
private readonly MouseHookListener m_MouseHookManager;
public TestFormHookListeners()
{
InitializeComponent();
//m_KeyboardHookManager = new KeyboardHookListener(new GlobalHooker());
//m_KeyboardHookManager.Enabled = true;
m_MouseHookManager = new MouseHookListener( new GlobalHooker() ) { Enabled = true };
HotKeySetCollection hkscoll = new HotKeySetCollection();
m_KeyboardHookManager = new HotKeySetsListener( hkscoll, new GlobalHooker() ) { Enabled = true };
BuildHotKeyTests( hkscoll );
}
private void BuildHotKeyTests( HotKeySetCollection hkscoll )
{
//Hot Keys are enabled by default. Use the Enabled property to adjust.
hkscoll.Add( BindHotKeySet( new[] { Keys.T, Keys.LShiftKey }, null, OnHotKeyDownOnce1, OnHotKeyDownHold1, OnHotKeyUp1, "test1" ) );
hkscoll.Add( BindHotKeySet( new[] { Keys.T, Keys.LControlKey, Keys.RControlKey }, new[] { Keys.LControlKey, Keys.RControlKey }, OnHotKeyDownGeneral2, OnHotKeyDownGeneral2, OnHotKeyUp1, "test2" ) );
}
private static HotKeySet BindHotKeySet( IEnumerable<Keys> ks,
IEnumerable<Keys> xorKeys,
HotKeySet.HotKeyHandler onEventDownOnce,
HotKeySet.HotKeyHandler onEventDownHold,
HotKeySet.HotKeyHandler onEventUp,
string name )
{
//Declare ALL Keys that will be available in this set, including any keys you want to register as an either/or subset
HotKeySet hks = new HotKeySet( ks );
//Indicates that the keys in this array will be treated as an OR rather than AND: LShiftKey or RShiftKey
//The keys MUST be a subset of the ks Keys array.
if ( hks.RegisterExclusiveOrKey( xorKeys ) == Keys.None ) //Keys.None indicates an error
{
MessageBox.Show( null, @"Unable to register subset: " + String.Join( ", ", xorKeys ),
@"Subset registration error", MessageBoxButtons.OK, MessageBoxIcon.Error );
}
hks.OnHotKeysDownOnce += onEventDownOnce; //The first time the key is down
hks.OnHotKeysDownHold += onEventDownHold; //Fired as long as the user holds the hot keys down but is not fired the first time.
hks.OnHotKeysUp += onEventUp; //Whenever a key from the set is no longer being held down
hks.Name = ( name ?? String.Empty );
return hks;
}
private void GeneralHotKeyEvent( object sender, DateTime timeTriggered, string eventType )
{
HotKeySet hks = sender as HotKeySet;
string kstring = String.Join( ", ", hks.HotKeys );
Log( String.Format( "{0}: {2} {1} - {3}\r\n", timeTriggered.TimeOfDay, eventType, hks.Name, kstring ) );
}
private void OnHotKeyDownGeneral2( object sender, HotKeyArgs e )
{
GeneralHotKeyEvent( sender, e.Time, "ONCE/HOLD" );
}
private void OnHotKeyDownOnce1( object sender, HotKeyArgs e )
{
GeneralHotKeyEvent( sender, e.Time, "ONCE" );
}
private void OnHotKeyDownHold1( object sender, HotKeyArgs e )
{
GeneralHotKeyEvent( sender, e.Time, "HOLD" );
}
private void OnHotKeyUp1( object sender, HotKeyArgs e )
{
GeneralHotKeyEvent( sender, e.Time, "UP" );
}
+54
View File
@@ -0,0 +1,54 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Windows.Forms;
namespace Gma.System.MouseKeyHook
{
/// <summary>
/// Provides keyboard events
/// </summary>
public interface IKeyboardEvents
{
/// <summary>
/// Occurs when a key is pressed.
/// </summary>
event KeyEventHandler KeyDown;
/// <summary>
/// Occurs when a key is pressed.
/// </summary>
/// <remarks>
/// Key events occur in the following order:
/// <list type="number">
/// <item>KeyDown</item>
/// <item>KeyPress</item>
/// <item>KeyDownTxt</item>
/// <item>KeyUp</item>
/// </list>
/// The KeyPress event is not raised by non-character keys; however, the non-character keys do raise the KeyDown and
/// KeyUp events.
/// Use the KeyChar property to sample keystrokes at run time and to consume or modify a subset of common keystrokes.
/// To handle keyboard events only in your application and not enable other applications to receive keyboard events,
/// set the <see cref="KeyPressEventArgs.Handled" /> property in your form's KeyPress event-handling method to
/// <b>true</b>.
/// </remarks>
event KeyPressEventHandler KeyPress;
/// <summary>
/// Occurs when a key is pressed, includes the keystroke characters if any
/// </summary>
event EventHandler<KeyDownTxtEventArgs> KeyDownTxt;
/// <summary>
/// Occurs when a key is released.
/// </summary>
event KeyEventHandler KeyUp;
event EventHandler<KeyEventArgsExt> KeyDownExt;
event EventHandler<KeyEventArgsExt> KeyUpExt;
}
}
@@ -0,0 +1,15 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
namespace Gma.System.MouseKeyHook
{
/// <summary>
/// Provides keyboard and mouse events.
/// </summary>
public interface IKeyboardMouseEvents : IKeyboardEvents, IMouseEvents, IDisposable
{
}
}
+124
View File
@@ -0,0 +1,124 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Windows.Forms;
namespace Gma.System.MouseKeyHook
{
/// <summary>
/// Provides all mouse events.
/// </summary>
public interface IMouseEvents
{
/// <summary>
/// Occurs when the mouse pointer is moved.
/// </summary>
event MouseEventHandler MouseMove;
/// <summary>
/// Occurs when the mouse pointer is moved.
/// </summary>
/// <remarks>
/// This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
/// suppress further processing of mouse movement in other applications.
/// </remarks>
event EventHandler<MouseEventExtArgs> MouseMoveExt;
/// <summary>
/// Occurs when a click was performed by the mouse.
/// </summary>
event MouseEventHandler MouseClick;
/// <summary>
/// Occurs when the mouse a mouse button is pressed.
/// </summary>
event MouseEventHandler MouseDown;
/// <summary>
/// Occurs when the mouse a mouse button is pressed.
/// </summary>
/// <remarks>
/// This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
/// suppress further processing of mouse click in other applications.
/// </remarks>
event EventHandler<MouseEventExtArgs> MouseDownExt;
/// <summary>
/// Occurs when a mouse button is released.
/// </summary>
event MouseEventHandler MouseUp;
/// <summary>
/// Occurs when a mouse button is released.
/// </summary>
/// <remarks>
/// This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
/// suppress further processing of mouse click in other applications.
/// </remarks>
event EventHandler<MouseEventExtArgs> MouseUpExt;
/// <summary>
/// Occurs when the mouse wheel moves.
/// </summary>
event MouseEventHandler MouseWheel;
/// <summary>
/// Occurs when the mouse wheel moves horizontally.
/// </summary>
event MouseEventHandler MouseHWheel;
/// <summary>
/// Occurs when the mouse wheel moves.
/// </summary>
/// <remarks>
/// This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
/// suppress further processing of mouse wheel moves in other applications.
/// </remarks>
event EventHandler<MouseEventExtArgs> MouseWheelExt;
/// <summary>
/// Occurs when the mouse wheel moves.
/// </summary>
/// <remarks>
/// This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
/// suppress further processing of horizontal mouse wheel moves in other applications.
/// </remarks>
event EventHandler<MouseEventExtArgs> MouseHWheelExt;
/// <summary>
/// Occurs when a mouse button is double-clicked.
/// </summary>
event MouseEventHandler MouseDoubleClick;
/// <summary>
/// Occurs when a drag event has started (left button held down whilst moving more than the system drag threshold).
/// </summary>
event MouseEventHandler MouseDragStarted;
/// <summary>
/// Occurs when a drag event has started (left button held down whilst moving more than the system drag threshold).
/// </summary>
/// <remarks>
/// This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
/// suppress further processing of mouse movement in other applications.
/// </remarks>
event EventHandler<MouseEventExtArgs> MouseDragStartedExt;
/// <summary>
/// Occurs when a drag event has completed.
/// </summary>
event MouseEventHandler MouseDragFinished;
/// <summary>
/// Occurs when a drag event has completed.
/// </summary>
/// <remarks>
/// This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
/// suppress further processing of mouse movement in other applications.
/// </remarks>
event EventHandler<MouseEventExtArgs> MouseDragFinishedExt;
}
}
@@ -0,0 +1,19 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
namespace Gma.System.MouseKeyHook.Implementation
{
internal class AppEventFacade : EventFacade
{
protected override MouseListener CreateMouseListener()
{
return new AppMouseListener();
}
protected override KeyListener CreateKeyListener()
{
return new AppKeyListener();
}
}
}
@@ -0,0 +1,27 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System.Collections.Generic;
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
internal class AppKeyListener : KeyListener
{
public AppKeyListener()
: base(HookHelper.HookAppKeyboard)
{
}
protected override IEnumerable<KeyPressEventArgsExt> GetPressEventArgs(CallbackData data)
{
return KeyPressEventArgsExt.FromRawDataApp(data);
}
protected override KeyEventArgsExt GetDownUpEventArgs(CallbackData data)
{
return KeyEventArgsExt.FromRawDataApp(data);
}
}
}
@@ -0,0 +1,21 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
internal class AppMouseListener : MouseListener
{
public AppMouseListener()
: base(HookHelper.HookAppMouse)
{
}
protected override MouseEventExtArgs GetEventArgs(CallbackData data)
{
return MouseEventExtArgs.FromRawDataApp(data);
}
}
}
@@ -0,0 +1,26 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
internal abstract class BaseListener : IDisposable
{
protected BaseListener(Subscribe subscribe)
{
Handle = subscribe(Callback);
}
protected HookResult Handle { get; set; }
public void Dispose()
{
Handle.Dispose();
}
protected abstract bool Callback(CallbackData data);
}
}
@@ -0,0 +1,33 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System.Windows.Forms;
namespace Gma.System.MouseKeyHook.Implementation
{
internal class ButtonSet
{
private MouseButtons m_Set;
public ButtonSet()
{
m_Set = MouseButtons.None;
}
public void Add(MouseButtons element)
{
m_Set |= element;
}
public void Remove(MouseButtons element)
{
m_Set &= ~element;
}
public bool Contains(MouseButtons element)
{
return (m_Set & element) != MouseButtons.None;
}
}
}
@@ -0,0 +1,10 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
internal delegate bool Callback(CallbackData data);
}
@@ -0,0 +1,75 @@
// This code is distributed under MIT license.
// Copyright (c) 2010-2018 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Gma.System.MouseKeyHook.Implementation
{
internal class Chord : IEnumerable<Keys>
{
private readonly Keys[] _keys;
internal Chord(IEnumerable<Keys> additionalKeys)
{
_keys = additionalKeys.Select(k => k.Normalize()).OrderBy(k => k).ToArray();
}
public int Count
{
get { return _keys.Length; }
}
public IEnumerator<Keys> GetEnumerator()
{
return _keys.Cast<Keys>().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public override string ToString()
{
return string.Join("+", _keys);
}
public static Chord FromString(string chord)
{
var parts = chord
.Split('+')
.Select(p => Enum.Parse(typeof(Keys), p))
.Cast<Keys>();
var stack = new Stack<Keys>(parts);
return new Chord(stack);
}
protected bool Equals(Chord other)
{
if (_keys.Length != other._keys.Length) return false;
return _keys.SequenceEqual(other._keys);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Chord) obj);
}
public override int GetHashCode()
{
unchecked
{
return (_keys.Length + 13) ^
((_keys.Length != 0 ? (int) _keys[0] ^ (int) _keys[_keys.Length - 1] : 0) * 397);
}
}
}
}
@@ -0,0 +1,174 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Windows.Forms;
namespace Gma.System.MouseKeyHook.Implementation
{
internal abstract class EventFacade : IKeyboardMouseEvents
{
private KeyListener m_KeyListenerCache;
private MouseListener m_MouseListenerCache;
public event KeyEventHandler KeyDown
{
add { GetKeyListener().KeyDown += value; }
remove { GetKeyListener().KeyDown -= value; }
}
public event KeyPressEventHandler KeyPress
{
add { GetKeyListener().KeyPress += value; }
remove { GetKeyListener().KeyPress -= value; }
}
public event EventHandler<KeyDownTxtEventArgs> KeyDownTxt
{
add { GetKeyListener().KeyDownTxt += value; }
remove { GetKeyListener().KeyDownTxt -= value; }
}
public event KeyEventHandler KeyUp
{
add { GetKeyListener().KeyUp += value; }
remove { GetKeyListener().KeyUp -= value; }
}
public event EventHandler<KeyEventArgsExt> KeyDownExt
{
add { GetKeyListener().KeyDownExt += value; }
remove { GetKeyListener().KeyDownExt -= value; }
}
public event EventHandler<KeyEventArgsExt> KeyUpExt
{
add { GetKeyListener().KeyUpExt += value; }
remove { GetKeyListener().KeyUpExt -= value; }
}
public event MouseEventHandler MouseMove
{
add { GetMouseListener().MouseMove += value; }
remove { GetMouseListener().MouseMove -= value; }
}
public event EventHandler<MouseEventExtArgs> MouseMoveExt
{
add { GetMouseListener().MouseMoveExt += value; }
remove { GetMouseListener().MouseMoveExt -= value; }
}
public event MouseEventHandler MouseClick
{
add { GetMouseListener().MouseClick += value; }
remove { GetMouseListener().MouseClick -= value; }
}
public event MouseEventHandler MouseDown
{
add { GetMouseListener().MouseDown += value; }
remove { GetMouseListener().MouseDown -= value; }
}
public event EventHandler<MouseEventExtArgs> MouseDownExt
{
add { GetMouseListener().MouseDownExt += value; }
remove { GetMouseListener().MouseDownExt -= value; }
}
public event MouseEventHandler MouseUp
{
add { GetMouseListener().MouseUp += value; }
remove { GetMouseListener().MouseUp -= value; }
}
public event EventHandler<MouseEventExtArgs> MouseUpExt
{
add { GetMouseListener().MouseUpExt += value; }
remove { GetMouseListener().MouseUpExt -= value; }
}
public event MouseEventHandler MouseWheel
{
add { GetMouseListener().MouseWheel += value; }
remove { GetMouseListener().MouseWheel -= value; }
}
public event EventHandler<MouseEventExtArgs> MouseWheelExt
{
add { GetMouseListener().MouseWheelExt += value; }
remove { GetMouseListener().MouseWheelExt -= value; }
}
public event MouseEventHandler MouseHWheel
{
add { GetMouseListener().MouseHWheel += value; }
remove { GetMouseListener().MouseHWheel -= value; }
}
public event EventHandler<MouseEventExtArgs> MouseHWheelExt
{
add { GetMouseListener().MouseHWheelExt += value; }
remove { GetMouseListener().MouseHWheelExt -= value; }
}
public event MouseEventHandler MouseDoubleClick
{
add { GetMouseListener().MouseDoubleClick += value; }
remove { GetMouseListener().MouseDoubleClick -= value; }
}
public event MouseEventHandler MouseDragStarted
{
add { GetMouseListener().MouseDragStarted += value; }
remove { GetMouseListener().MouseDragStarted -= value; }
}
public event EventHandler<MouseEventExtArgs> MouseDragStartedExt
{
add { GetMouseListener().MouseDragStartedExt += value; }
remove { GetMouseListener().MouseDragStartedExt -= value; }
}
public event MouseEventHandler MouseDragFinished
{
add { GetMouseListener().MouseDragFinished += value; }
remove { GetMouseListener().MouseDragFinished -= value; }
}
public event EventHandler<MouseEventExtArgs> MouseDragFinishedExt
{
add { GetMouseListener().MouseDragFinishedExt += value; }
remove { GetMouseListener().MouseDragFinishedExt -= value; }
}
public void Dispose()
{
if (m_MouseListenerCache != null) m_MouseListenerCache.Dispose();
if (m_KeyListenerCache != null) m_KeyListenerCache.Dispose();
}
private KeyListener GetKeyListener()
{
var target = m_KeyListenerCache;
if (target != null) return target;
target = CreateKeyListener();
m_KeyListenerCache = target;
return target;
}
private MouseListener GetMouseListener()
{
var target = m_MouseListenerCache;
if (target != null) return target;
target = CreateMouseListener();
m_MouseListenerCache = target;
return target;
}
protected abstract MouseListener CreateMouseListener();
protected abstract KeyListener CreateKeyListener();
}
}
@@ -0,0 +1,19 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
namespace Gma.System.MouseKeyHook.Implementation
{
internal class GlobalEventFacade : EventFacade
{
protected override MouseListener CreateMouseListener()
{
return new GlobalMouseListener();
}
protected override KeyListener CreateKeyListener()
{
return new GlobalKeyListener();
}
}
}
@@ -0,0 +1,27 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System.Collections.Generic;
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
internal class GlobalKeyListener : KeyListener
{
public GlobalKeyListener()
: base(HookHelper.HookGlobalKeyboard)
{
}
protected override IEnumerable<KeyPressEventArgsExt> GetPressEventArgs(CallbackData data)
{
return KeyPressEventArgsExt.FromRawDataGlobal(data);
}
protected override KeyEventArgsExt GetDownUpEventArgs(CallbackData data)
{
return KeyEventArgsExt.FromRawDataGlobal(data);
}
}
}
@@ -0,0 +1,75 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Windows.Forms;
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
internal class GlobalMouseListener : MouseListener
{
private readonly int m_SystemDoubleClickTime;
private readonly int m_xDoubleClickThreshold;
private readonly int m_yDoubleClickThreshold;
private MouseButtons m_PreviousClicked;
private Point m_PreviousClickedPosition;
private int m_PreviousClickedTime;
public GlobalMouseListener()
: base(HookHelper.HookGlobalMouse)
{
m_SystemDoubleClickTime = MouseNativeMethods.GetDoubleClickTime();
m_xDoubleClickThreshold = NativeMethods.GetXDoubleClickThreshold();
m_yDoubleClickThreshold = NativeMethods.GetYDoubleClickThreshold();
}
protected override void ProcessDown(ref MouseEventExtArgs e)
{
if (IsDoubleClick(e))
e = e.ToDoubleClickEventArgs();
else
StartDoubleClickWaiting(e);
base.ProcessDown(ref e);
}
protected override void ProcessUp(ref MouseEventExtArgs e)
{
base.ProcessUp(ref e);
if (e.Clicks == 2)
StopDoubleClickWaiting();
}
private void StartDoubleClickWaiting(MouseEventExtArgs e)
{
m_PreviousClicked = e.Button;
m_PreviousClickedTime = e.Timestamp;
m_PreviousClickedPosition = e.Point;
}
private void StopDoubleClickWaiting()
{
m_PreviousClicked = MouseButtons.None;
m_PreviousClickedTime = 0;
m_PreviousClickedPosition = m_UninitialisedPoint;
}
private bool IsDoubleClick(MouseEventExtArgs e)
{
var isXMoving = Math.Abs(e.Point.X - m_PreviousClickedPosition.X) > m_xDoubleClickThreshold;
var isYMoving = Math.Abs(e.Point.Y - m_PreviousClickedPosition.Y) > m_yDoubleClickThreshold;
return
e.Button == m_PreviousClicked &&
!isXMoving &&
!isYMoving &&
e.Timestamp - m_PreviousClickedTime <= m_SystemDoubleClickTime;
}
protected override MouseEventExtArgs GetEventArgs(CallbackData data)
{
return MouseEventExtArgs.FromRawDataGlobal(data);
}
}
}
@@ -0,0 +1,122 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
internal abstract class KeyListener : BaseListener, IKeyboardEvents
{
protected KeyListener(Subscribe subscribe)
: base(subscribe)
{
}
public event KeyEventHandler KeyDown;
public event KeyPressEventHandler KeyPress;
public event EventHandler<KeyDownTxtEventArgs> KeyDownTxt;
public event KeyEventHandler KeyUp;
public event EventHandler<KeyEventArgsExt> KeyDownExt;
public event EventHandler<KeyEventArgsExt> KeyUpExt;
public void InvokeKeyDown(KeyEventArgsExt e)
{
OnKeyDownExt(e);
OnKeyDown(e);
}
private void OnKeyDown(KeyEventArgsExt e)
{
var handler = KeyDown;
if (handler == null || e.Handled || !e.IsKeyDown)
return;
handler(this, e);
}
private void OnKeyDownExt(KeyEventArgsExt e)
{
var handler = KeyDownExt;
if (handler == null || e.Handled || !e.IsKeyDown)
return;
handler(this, e);
}
public void InvokeKeyPress(KeyPressEventArgsExt e)
{
var handler = KeyPress;
if (handler == null || e.Handled || e.IsNonChar)
return;
handler(this, e);
}
public void InvokeKeyDownTxt(KeyDownTxtEventArgs e)
{
var handler = KeyDownTxt;
if (handler == null || e.KeyEvent.Handled || !e.KeyEvent.IsKeyDown)
return;
handler(this, e);
}
public void InvokeKeyUp(KeyEventArgsExt e)
{
OnKeyUpExt(e);
OnKeyUp(e);
}
private void OnKeyUp(KeyEventArgsExt e)
{
var handler = KeyUp;
if (handler == null || e.Handled || !e.IsKeyUp)
return;
handler(this, e);
}
private void OnKeyUpExt(KeyEventArgsExt e)
{
var handler = KeyUpExt;
if (handler == null || e.Handled || !e.IsKeyUp)
return;
handler(this, e);
}
protected override bool Callback(CallbackData data)
{
var eDownUp = GetDownUpEventArgs(data);
InvokeKeyDown(eDownUp);
if (KeyPress != null || KeyDownTxt != null)
{
var pressEventArgs = GetPressEventArgs(data).ToList();
foreach (var pressEventArg in pressEventArgs)
InvokeKeyPress(pressEventArg);
var downTxtEventArgs = GetDownTxtEventArgs(eDownUp, pressEventArgs);
InvokeKeyDownTxt(downTxtEventArgs);
}
InvokeKeyUp(eDownUp);
return !eDownUp.Handled;
}
private KeyDownTxtEventArgs GetDownTxtEventArgs(KeyEventArgsExt eDownUp, IEnumerable<KeyPressEventArgsExt> pressEventArgs)
{
var charsCollection = pressEventArgs.Where(e => !e.IsNonChar).Select(e => e.KeyChar);
var chars = string.Join(string.Empty, charsCollection);
return new KeyDownTxtEventArgs(eDownUp, chars);
}
protected abstract IEnumerable<KeyPressEventArgsExt> GetPressEventArgs(CallbackData data);
protected abstract KeyEventArgsExt GetDownUpEventArgs(CallbackData data);
}
}
@@ -0,0 +1,112 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
/// <summary>
/// Contains a snapshot of a keyboard state at certain moment and provides methods
/// of querying whether specific keys are pressed or locked.
/// </summary>
/// <remarks>
/// This class is basically a managed wrapper of GetKeyboardState API function
/// http://msdn.microsoft.com/en-us/library/ms646299
/// </remarks>
public class KeyboardState
{
private readonly byte[] m_KeyboardStateNative;
private KeyboardState(byte[] keyboardStateNative)
{
m_KeyboardStateNative = keyboardStateNative;
}
/// <summary>
/// Makes a snapshot of a keyboard state to the moment of call and returns an
/// instance of <see cref="KeyboardState" /> class.
/// </summary>
/// <returns>An instance of <see cref="KeyboardState" /> class representing a snapshot of keyboard state at certain moment.</returns>
public static KeyboardState GetCurrent()
{
var keyboardStateNative = new byte[256];
KeyboardNativeMethods.GetKeyboardState(keyboardStateNative);
return new KeyboardState(keyboardStateNative);
}
internal byte[] GetNativeState()
{
return m_KeyboardStateNative;
}
/// <summary>
/// Indicates whether specified key was down at the moment when snapshot was created or not.
/// </summary>
/// <param name="key">Key (corresponds to the virtual code of the key)</param>
/// <returns><b>true</b> if key was down, <b>false</b> - if key was up.</returns>
public bool IsDown(Keys key)
{
if ((int)key < 256) return IsDownRaw(key);
if (key == Keys.Alt) return IsDownRaw(Keys.LMenu) || IsDownRaw(Keys.RMenu);
if (key == Keys.Shift) return IsDownRaw(Keys.LShiftKey) || IsDownRaw(Keys.RShiftKey);
if (key == Keys.Control) return IsDownRaw(Keys.LControlKey) || IsDownRaw(Keys.RControlKey);
return false;
}
private bool IsDownRaw(Keys key)
{
var keyState = GetKeyState(key);
var isDown = GetHighBit(keyState);
return isDown;
}
/// <summary>
/// Indicate weather specified key was toggled at the moment when snapshot was created or not.
/// </summary>
/// <param name="key">Key (corresponds to the virtual code of the key)</param>
/// <returns>
/// <b>true</b> if toggle key like (CapsLock, NumLocke, etc.) was on. <b>false</b> if it was off.
/// Ordinal (non toggle) keys return always false.
/// </returns>
public bool IsToggled(Keys key)
{
var keyState = GetKeyState(key);
var isToggled = GetLowBit(keyState);
return isToggled;
}
/// <summary>
/// Indicates weather every of specified keys were down at the moment when snapshot was created.
/// The method returns false if even one of them was up.
/// </summary>
/// <param name="keys">Keys to verify whether they were down or not.</param>
/// <returns><b>true</b> - all were down. <b>false</b> - at least one was up.</returns>
public bool AreAllDown(IEnumerable<Keys> keys)
{
return keys.All(IsDown);
}
private byte GetKeyState(Keys key)
{
var virtualKeyCode = (int) key;
if (virtualKeyCode < 0 || virtualKeyCode > 255)
throw new ArgumentOutOfRangeException("key", key, "The value must be between 0 and 255.");
return m_KeyboardStateNative[virtualKeyCode];
}
private static bool GetHighBit(byte value)
{
return value >> 7 != 0;
}
private static bool GetLowBit(byte value)
{
return (value & 1) != 0;
}
}
}
@@ -0,0 +1,22 @@
// This code is distributed under MIT license.
// Copyright (c) 2010-2018 George Mamaladze
// See license.txt or https://mit-license.org/
using System.Windows.Forms;
namespace Gma.System.MouseKeyHook.Implementation
{
internal static class KeysExtensions
{
public static Keys Normalize(this Keys key)
{
if ((key & Keys.LControlKey) == Keys.LControlKey ||
(key & Keys.RControlKey) == Keys.RControlKey) return Keys.Control;
if ((key & Keys.LShiftKey) == Keys.LShiftKey ||
(key & Keys.RShiftKey) == Keys.RShiftKey) return Keys.Shift;
if ((key & Keys.LMenu) == Keys.LMenu ||
(key & Keys.RMenu) == Keys.RMenu) return Keys.Alt;
return key;
}
}
}
@@ -0,0 +1,328 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
// Because it is a P/Invoke method, 'GetSystemMetrics(int)'
// should be defined in a class named NativeMethods, SafeNativeMethods,
// or UnsafeNativeMethods.
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
internal static class NativeMethods
{
private const int SM_SWAPBUTTON = 23;
private const int SM_CXDRAG = 68;
private const int SM_CYDRAG = 69;
private const int SM_CXDOUBLECLK = 36;
private const int SM_CYDOUBLECLK = 37;
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int index);
public static int GetSwapButtonThreshold()
{
return GetSystemMetrics(SM_SWAPBUTTON);
}
public static int GetXDragThreshold()
{
return GetSystemMetrics(SM_CXDRAG) / 2 + 1;
}
public static int GetYDragThreshold()
{
return GetSystemMetrics(SM_CYDRAG) / 2 + 1;
}
public static int GetXDoubleClickThreshold()
{
return GetSystemMetrics(SM_CXDOUBLECLK) / 2 + 1;
}
public static int GetYDoubleClickThreshold()
{
return GetSystemMetrics(SM_CYDOUBLECLK) / 2 + 1;
}
}
internal abstract class MouseListener : BaseListener, IMouseEvents
{
private readonly ButtonSet m_DoubleDown;
private readonly ButtonSet m_SingleDown;
protected readonly Point m_UninitialisedPoint = new Point(-99999, -99999);
private readonly int m_SwapButtonThreshold;
private readonly int m_xDragThreshold;
private readonly int m_yDragThreshold;
private Point m_DragStartPosition;
private bool m_IsDragging;
private Point m_PreviousPosition;
protected MouseListener(Subscribe subscribe)
: base(subscribe)
{
m_SwapButtonThreshold = NativeMethods.GetSwapButtonThreshold();
m_xDragThreshold = NativeMethods.GetXDragThreshold();
m_yDragThreshold = NativeMethods.GetYDragThreshold();
m_IsDragging = false;
m_PreviousPosition = m_UninitialisedPoint;
m_DragStartPosition = m_UninitialisedPoint;
m_DoubleDown = new ButtonSet();
m_SingleDown = new ButtonSet();
}
public event MouseEventHandler MouseMove;
public event EventHandler<MouseEventExtArgs> MouseMoveExt;
public event MouseEventHandler MouseClick;
public event MouseEventHandler MouseDown;
public event EventHandler<MouseEventExtArgs> MouseDownExt;
public event MouseEventHandler MouseUp;
public event EventHandler<MouseEventExtArgs> MouseUpExt;
public event MouseEventHandler MouseWheel;
public event EventHandler<MouseEventExtArgs> MouseWheelExt;
public event MouseEventHandler MouseHWheel;
public event EventHandler<MouseEventExtArgs> MouseHWheelExt;
public event MouseEventHandler MouseDoubleClick;
public event MouseEventHandler MouseDragStarted;
public event EventHandler<MouseEventExtArgs> MouseDragStartedExt;
public event MouseEventHandler MouseDragFinished;
public event EventHandler<MouseEventExtArgs> MouseDragFinishedExt;
protected override bool Callback(CallbackData data)
{
data.MSwapButton = m_SwapButtonThreshold;
var e = GetEventArgs(data);
if (e.IsMouseButtonDown)
ProcessDown(ref e);
if (e.IsMouseButtonUp)
ProcessUp(ref e);
if (e.WheelScrolled)
{
if (e.IsHorizontalWheel)
ProcessHWheel(ref e);
else
ProcessWheel(ref e);
}
if (HasMoved(e.Point))
ProcessMove(ref e);
ProcessDrag(ref e);
return !e.Handled;
}
protected abstract MouseEventExtArgs GetEventArgs(CallbackData data);
protected virtual void ProcessWheel(ref MouseEventExtArgs e)
{
OnWheel(e);
OnWheelExt(e);
}
protected virtual void ProcessHWheel(ref MouseEventExtArgs e)
{
OnHWheel(e);
OnHWheelExt(e);
}
protected virtual void ProcessDown(ref MouseEventExtArgs e)
{
OnDown(e);
OnDownExt(e);
if (e.Handled)
return;
if (e.Clicks == 2)
m_DoubleDown.Add(e.Button);
if (e.Clicks == 1)
m_SingleDown.Add(e.Button);
}
protected virtual void ProcessUp(ref MouseEventExtArgs e)
{
OnUp(e);
OnUpExt(e);
if (e.Handled)
return;
if (m_SingleDown.Contains(e.Button))
{
OnClick(e);
m_SingleDown.Remove(e.Button);
}
if (m_DoubleDown.Contains(e.Button))
{
e = e.ToDoubleClickEventArgs();
OnDoubleClick(e);
m_DoubleDown.Remove(e.Button);
}
}
private void ProcessMove(ref MouseEventExtArgs e)
{
m_PreviousPosition = e.Point;
OnMove(e);
OnMoveExt(e);
}
private void ProcessDrag(ref MouseEventExtArgs e)
{
if (m_SingleDown.Contains(MouseButtons.Left))
{
if (m_DragStartPosition.Equals(m_UninitialisedPoint))
m_DragStartPosition = e.Point;
ProcessDragStarted(ref e);
}
else
{
m_DragStartPosition = m_UninitialisedPoint;
ProcessDragFinished(ref e);
}
}
private void ProcessDragStarted(ref MouseEventExtArgs e)
{
if (!m_IsDragging)
{
var isXDragging = Math.Abs(e.Point.X - m_DragStartPosition.X) > m_xDragThreshold;
var isYDragging = Math.Abs(e.Point.Y - m_DragStartPosition.Y) > m_yDragThreshold;
m_IsDragging = isXDragging || isYDragging;
if (m_IsDragging)
{
var dragArgs = new MouseEventExtArgs(e.Button, e.Clicks, m_DragStartPosition, e.Delta, e.Timestamp, e.IsMouseButtonDown, e.IsMouseButtonUp, e.IsHorizontalWheel);
OnDragStarted(dragArgs);
OnDragStartedExt(dragArgs);
}
}
}
private void ProcessDragFinished(ref MouseEventExtArgs e)
{
if (m_IsDragging)
{
OnDragFinished(e);
OnDragFinishedExt(e);
m_IsDragging = false;
}
}
private bool HasMoved(Point actualPoint)
{
return m_PreviousPosition != actualPoint;
}
protected virtual void OnMove(MouseEventArgs e)
{
var handler = MouseMove;
if (handler != null) handler(this, e);
}
protected virtual void OnMoveExt(MouseEventExtArgs e)
{
var handler = MouseMoveExt;
if (handler != null) handler(this, e);
}
protected virtual void OnClick(MouseEventArgs e)
{
var handler = MouseClick;
if (handler != null) handler(this, e);
}
protected virtual void OnDown(MouseEventArgs e)
{
var handler = MouseDown;
if (handler != null) handler(this, e);
}
protected virtual void OnDownExt(MouseEventExtArgs e)
{
var handler = MouseDownExt;
if (handler != null) handler(this, e);
}
protected virtual void OnUp(MouseEventArgs e)
{
var handler = MouseUp;
if (handler != null) handler(this, e);
}
protected virtual void OnUpExt(MouseEventExtArgs e)
{
var handler = MouseUpExt;
if (handler != null) handler(this, e);
}
protected virtual void OnWheel(MouseEventArgs e)
{
var handler = MouseWheel;
if (handler != null) handler(this, e);
}
protected virtual void OnWheelExt(MouseEventExtArgs e)
{
var handler = MouseWheelExt;
if (handler != null) handler(this, e);
}
protected virtual void OnHWheel(MouseEventArgs e)
{
var handler = MouseHWheel;
if (handler != null) handler(this, e);
}
protected virtual void OnHWheelExt(MouseEventExtArgs e)
{
var handler = MouseHWheelExt;
if (handler != null) handler(this, e);
}
protected virtual void OnDoubleClick(MouseEventArgs e)
{
var handler = MouseDoubleClick;
if (handler != null) handler(this, e);
}
protected virtual void OnDragStarted(MouseEventArgs e)
{
var handler = MouseDragStarted;
if (handler != null) handler(this, e);
}
protected virtual void OnDragStartedExt(MouseEventExtArgs e)
{
var handler = MouseDragStartedExt;
if (handler != null) handler(this, e);
}
protected virtual void OnDragFinished(MouseEventArgs e)
{
var handler = MouseDragFinished;
if (handler != null) handler(this, e);
}
protected virtual void OnDragFinishedExt(MouseEventExtArgs e)
{
var handler = MouseDragFinishedExt;
if (handler != null) handler(this, e);
}
}
}
@@ -0,0 +1,10 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook.Implementation
{
internal delegate HookResult Subscribe(Callback callbck);
}
@@ -0,0 +1,108 @@
// This code is distributed under MIT license.
// Copyright (c) 2010-2018 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Collections.Generic;
using System.Linq;
using Gma.System.MouseKeyHook.Implementation;
namespace Gma.System.MouseKeyHook
{
/// <summary>
/// Extension methods to detect key combinations
/// </summary>
public static class KeyCombinationExtensions
{
/// <summary>
/// Detects a key or key combination and triggers the corresponding action.
/// </summary>
/// <param name="source">
/// An instance of Global or Application hook. Use <see cref="Hook.GlobalEvents" /> or <see cref="Hook.AppEvents" /> to
/// create it.
/// </param>
/// <param name="map">
/// This map contains the list of key combinations mapped to corresponding actions. You can use a dictionary initilizer
/// to easily create it.
/// Whenever a listed combination will be detected a corresponding action will be triggered.
/// </param>
/// <param name="reset">
/// This optional action will be executed when some key was pressed but it was not part of any wanted combinations.
/// </param>
public static void OnCombination(this IKeyboardEvents source,
IEnumerable<KeyValuePair<Combination, Action>> map, Action reset = null)
{
var watchlists = map.GroupBy(k => k.Key.TriggerKey)
.ToDictionary(g => g.Key, g => g.ToArray());
source.KeyDown += (sender, e) =>
{
KeyValuePair<Combination, Action>[] element;
var found = watchlists.TryGetValue(e.KeyCode.Normalize(), out element);
if (!found)
{
reset?.Invoke();
return;
}
var state = KeyboardState.GetCurrent();
var action = reset;
var maxLength = 0;
foreach (var current in element)
{
var matches = current.Key.Chord.All(state.IsDown);
if (!matches) continue;
if (maxLength > current.Key.ChordLength) continue;
maxLength = current.Key.ChordLength;
action = current.Value;
}
action?.Invoke();
};
}
/// <summary>
/// Detects a key or key combination sequence and triggers the corresponding action.
/// </summary>
/// <param name="source">
/// An instance of Global or Application hook. Use <see cref="Hook.GlobalEvents" /> or
/// <see cref="Hook.AppEvents" /> to create it.
/// </param>
/// <param name="map">
/// This map contains the list of sequences mapped to corresponding actions. You can use a dictionary initilizer to
/// easily create it.
/// Whenever a listed sequnce will be detected a corresponding action will be triggered. If two or more sequences match
/// the longest one will be used.
/// Example: sequences may A,B,C and B,C might be detected simultanously if user pressed first A then B then C. In this
/// case only action corresponding
/// to 'A,B,C' will be triggered.
/// </param>
public static void OnSequence(this IKeyboardEvents source, IEnumerable<KeyValuePair<Sequence, Action>> map)
{
var actBySeq = map.ToArray();
var endsWith = new Func<Queue<Combination>, Sequence, bool>((chords, sequence) =>
{
var skipCount = chords.Count - sequence.Length;
return skipCount >= 0 && chords.Skip(skipCount).SequenceEqual(sequence);
});
var max = actBySeq.Select(p => p.Key).Max(c => c.Length);
var min = actBySeq.Select(p => p.Key).Min(c => c.Length);
var buffer = new Queue<Combination>(max);
var wrapMap = actBySeq.SelectMany(p => p.Key).Select(c => new KeyValuePair<Combination, Action>(c, () =>
{
buffer.Enqueue(c);
if (buffer.Count > max) buffer.Dequeue();
if (buffer.Count < min) return;
//Invoke action corresponding to the longest matching sequence
actBySeq
.Where(pair => endsWith(buffer, pair.Key))
.OrderBy(pair => pair.Key.Length)
.Select(pair => pair.Value)
.LastOrDefault()
?.Invoke();
}));
OnCombination(source, wrapMap, buffer.Clear);
}
}
}
@@ -0,0 +1,16 @@
using System;
namespace Gma.System.MouseKeyHook
{
public class KeyDownTxtEventArgs : EventArgs
{
public KeyEventArgsExt KeyEvent { get; }
public string Chars { get; }
public KeyDownTxtEventArgs(KeyEventArgsExt keyEvent, string chars)
{
KeyEvent = keyEvent;
Chars = chars ?? string.Empty;
}
}
}
+153
View File
@@ -0,0 +1,153 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Gma.System.MouseKeyHook.Implementation;
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook
{
/// <summary>
/// Provides extended argument data for the <see cref='KeyListener.KeyDown' /> or
/// <see cref='KeyListener.KeyUp' /> event.
/// </summary>
public class KeyEventArgsExt : KeyEventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="KeyEventArgsExt" /> class.
/// </summary>
/// <param name="keyData"></param>
public KeyEventArgsExt(Keys keyData)
: base(keyData)
{
}
internal KeyEventArgsExt(Keys keyData, int scanCode, int timestamp, bool isKeyDown, bool isKeyUp,
bool isExtendedKey)
: this(keyData)
{
ScanCode = scanCode;
Timestamp = timestamp;
IsKeyDown = isKeyDown;
IsKeyUp = isKeyUp;
IsExtendedKey = isExtendedKey;
}
/// <summary>
/// The hardware scan code.
/// </summary>
public int ScanCode { get; }
/// <summary>
/// The system tick count of when the event occurred.
/// </summary>
public int Timestamp { get; }
/// <summary>
/// True if event signals key down..
/// </summary>
public bool IsKeyDown { get; }
/// <summary>
/// True if event signals key up.
/// </summary>
public bool IsKeyUp { get; }
/// <summary>
/// True if event signals, that the key is an extended key
/// </summary>
public bool IsExtendedKey { get; }
internal static KeyEventArgsExt FromRawDataApp(CallbackData data)
{
var wParam = data.WParam;
var lParam = data.LParam;
//http://msdn.microsoft.com/en-us/library/ms644984(v=VS.85).aspx
const uint maskKeydown = 0x40000000; // for bit 30
const uint maskKeyup = 0x80000000; // for bit 31
const uint maskExtendedKey = 0x1000000; // for bit 24
var timestamp = Environment.TickCount;
var flags = (uint) lParam.ToInt64();
//bit 30 Specifies the previous key state. The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
var wasKeyDown = (flags & maskKeydown) > 0;
//bit 31 Specifies the transition state. The value is 0 if the key is being pressed and 1 if it is being released.
var isKeyReleased = (flags & maskKeyup) > 0;
//bit 24 Specifies the extended key state. The value is 1 if the key is an extended key, otherwise the value is 0.
var isExtendedKey = (flags & maskExtendedKey) > 0;
var keyData = AppendModifierStates((Keys) wParam);
var scanCode = (int) (((flags & 0x10000) | (flags & 0x20000) | (flags & 0x40000) | (flags & 0x80000) |
(flags & 0x100000) | (flags & 0x200000) | (flags & 0x400000) | (flags & 0x800000)) >>
16);
var isKeyDown = !isKeyReleased;
var isKeyUp = wasKeyDown && isKeyReleased;
return new KeyEventArgsExt(keyData, scanCode, timestamp, isKeyDown, isKeyUp, isExtendedKey);
}
internal static KeyEventArgsExt FromRawDataGlobal(CallbackData data)
{
var wParam = data.WParam;
var lParam = data.LParam;
var keyboardHookStruct =
(KeyboardHookStruct) Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
var keyData = AppendModifierStates((Keys) keyboardHookStruct.VirtualKeyCode);
var keyCode = (int) wParam;
var isKeyDown = keyCode == Messages.WM_KEYDOWN || keyCode == Messages.WM_SYSKEYDOWN;
var isKeyUp = keyCode == Messages.WM_KEYUP || keyCode == Messages.WM_SYSKEYUP;
const uint maskExtendedKey = 0x1;
var isExtendedKey = (keyboardHookStruct.Flags & maskExtendedKey) > 0;
return new KeyEventArgsExt(keyData, keyboardHookStruct.ScanCode, keyboardHookStruct.Time, isKeyDown,
isKeyUp, isExtendedKey);
}
// # It is not possible to distinguish Keys.LControlKey and Keys.RControlKey when they are modifiers
// Check for Keys.Control instead
// Same for Shift and Alt(Menu)
// See more at http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.windowsforms/2008-04/msg00127.html #
// A shortcut to make life easier
private static bool CheckModifier(int vKey)
{
return (KeyboardNativeMethods.GetKeyState(vKey) & 0x8000) > 0;
}
private static Keys AppendModifierStates(Keys keyData)
{
// Is Control being held down?
var control = CheckModifier(KeyboardNativeMethods.VK_CONTROL);
// Is Shift being held down?
var shift = CheckModifier(KeyboardNativeMethods.VK_SHIFT);
// Is Alt being held down?
var alt = CheckModifier(KeyboardNativeMethods.VK_MENU);
// Windows keys
// # combine LWin and RWin key with other keys will potentially corrupt the data
// notable F5 | Keys.LWin == F12, see https://globalmousekeyhook.codeplex.com/workitem/1188
// and the KeyEventArgs.KeyData don't recognize combined data either
// Function (Fn) key
// # CANNOT determine state due to conversion inside keyboard
// See http://en.wikipedia.org/wiki/Fn_key#Technical_details #
return keyData |
(control ? Keys.Control : Keys.None) |
(shift ? Keys.Shift : Keys.None) |
(alt ? Keys.Alt : Keys.None);
}
}
}
+111
View File
@@ -0,0 +1,111 @@
// This code is distributed under MIT license.
// Copyright (c) 2015 George Mamaladze
// See license.txt or https://mit-license.org/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Gma.System.MouseKeyHook.Implementation;
using Gma.System.MouseKeyHook.WinApi;
namespace Gma.System.MouseKeyHook
{
/// <summary>
/// Provides extended data for the <see cref='KeyListener.KeyPress' /> event.
/// </summary>
public class KeyPressEventArgsExt : KeyPressEventArgs
{
internal KeyPressEventArgsExt(char keyChar, int timestamp)
: base(keyChar)
{
IsNonChar = keyChar == (char) 0x0;
Timestamp = timestamp;
}
/// <summary>
/// Initializes a new instance of the <see cref='KeyPressEventArgsExt' /> class.
/// </summary>
/// <param name="keyChar">
/// Character corresponding to the key pressed. 0 char if represents a system or functional non char
/// key.
/// </param>
public KeyPressEventArgsExt(char keyChar)
: this(keyChar, Environment.TickCount)
{
}
/// <summary>
/// True if represents a system or functional non char key.
/// </summary>
public bool IsNonChar { get; }
/// <summary>
/// The system tick count of when the event occurred.
/// </summary>
public int Timestamp { get; }
internal static IEnumerable<KeyPressEventArgsExt> FromRawDataApp(CallbackData data)
{
var wParam = data.WParam;
var lParam = data.LParam;
//http://msdn.microsoft.com/en-us/library/ms644984(v=VS.85).aspx
const uint maskKeydown = 0x40000000; // for bit 30
const uint maskKeyup = 0x80000000; // for bit 31
const uint maskScanCode = 0xff0000; // for bit 23-16
var flags = (uint) lParam.ToInt64();
//bit 30 Specifies the previous key state. The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
var wasKeyDown = (flags & maskKeydown) > 0;
//bit 31 Specifies the transition state. The value is 0 if the key is being pressed and 1 if it is being released.
var isKeyReleased = (flags & maskKeyup) > 0;
if (!wasKeyDown && !isKeyReleased)
yield break;
var virtualKeyCode = (int) wParam;
var scanCode = checked((int) (flags & maskScanCode));
const int fuState = 0;
char[] chars;
KeyboardNativeMethods.TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, out chars);
if (chars == null) yield break;
foreach (var ch in chars)
yield return new KeyPressEventArgsExt(ch);
}
internal static IEnumerable<KeyPressEventArgsExt> FromRawDataGlobal(CallbackData data)
{
var wParam = data.WParam;
var lParam = data.LParam;
if ((int) wParam != Messages.WM_KEYDOWN && (int) wParam != Messages.WM_SYSKEYDOWN)
yield break;
var keyboardHookStruct =
(KeyboardHookStruct) Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
var virtualKeyCode = keyboardHookStruct.VirtualKeyCode;
var scanCode = keyboardHookStruct.ScanCode;
var fuState = keyboardHookStruct.Flags;
if (virtualKeyCode == KeyboardNativeMethods.VK_PACKET)
{
var ch = (char) scanCode;
yield return new KeyPressEventArgsExt(ch, keyboardHookStruct.Time);
}
else
{
char[] chars;
KeyboardNativeMethods.TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, out chars);
if (chars == null) yield break;
foreach (var current in chars)
yield return new KeyPressEventArgsExt(current, keyboardHookStruct.Time);
}
}
}
}
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more