diff --git a/Ink Canvas/App.xaml.cs b/Ink Canvas/App.xaml.cs index 7c223af0..94f620e1 100644 --- a/Ink Canvas/App.xaml.cs +++ b/Ink Canvas/App.xaml.cs @@ -1,8 +1,10 @@ using Hardcodet.Wpf.TaskbarNotification; using Ink_Canvas.Helpers; +using Ink_Canvas.Properties; using iNKORE.UI.WPF.Modern.Controls; using Microsoft.Win32; using Newtonsoft.Json; +using Sentry; using System; using System.Diagnostics; using System.IO; @@ -18,10 +20,8 @@ using System.Windows.Input; using System.Windows.Threading; using Application = System.Windows.Application; using MessageBox = System.Windows.MessageBox; -using Ink_Canvas.Properties; using SplashScreen = Ink_Canvas.Windows.SplashScreen; using Timer = System.Threading.Timer; -using Sentry; namespace Ink_Canvas { @@ -1088,7 +1088,7 @@ namespace Ink_Canvas LogHelper.WriteLogToFile($"启动完成心跳已记录"); } LogHelper.WriteLogToFile($"启动时长: {(startupCompleteHeartbeat - appStartupStartTime).TotalSeconds:F2}秒"); - + if (_isSplashScreenShown) { SetSplashMessage("完成初始化..."); @@ -1226,8 +1226,8 @@ namespace Ink_Canvas if (!isStartupComplete && appStartupStartTime != DateTime.MinValue) { - DateTime startTime = _isSplashScreenShown && splashScreenStartTime != DateTime.MinValue - ? splashScreenStartTime + DateTime startTime = _isSplashScreenShown && splashScreenStartTime != DateTime.MinValue + ? splashScreenStartTime : appStartupStartTime; TimeSpan elapsedSinceStart = now - startTime; if (elapsedSinceStart >= StartupTimeout) @@ -1255,7 +1255,7 @@ namespace Ink_Canvas return; } } - + if (isStartupComplete && (now - lastHeartbeat).TotalSeconds > 10) { if (appStartupStartTime != DateTime.MinValue && (now - appStartupStartTime) < StartupTimeout) @@ -1397,7 +1397,7 @@ namespace Ink_Canvas string assemblyLocation = Assembly.GetExecutingAssembly().Location; string currentDir = Path.GetDirectoryName(assemblyLocation); - + for (int i = 0; i < 5; i++) { string dsnFilePath = Path.Combine(currentDir, "telemetry_dsn.txt"); @@ -1409,7 +1409,7 @@ namespace Ink_Canvas return dsn; } } - + DirectoryInfo parentDir = Directory.GetParent(currentDir); if (parentDir == null) { diff --git a/Ink Canvas/Helpers/AutoUpdateHelper.cs b/Ink Canvas/Helpers/AutoUpdateHelper.cs index b19cd786..33e31bd2 100644 --- a/Ink Canvas/Helpers/AutoUpdateHelper.cs +++ b/Ink Canvas/Helpers/AutoUpdateHelper.cs @@ -643,20 +643,20 @@ namespace Ink_Canvas.Helpers LogHelper.WriteLogToFile("AutoUpdate | 使用GitHub API调用"); var response = await client.GetStringAsync(apiUrl); var releases = JArray.Parse(response); - + if (releases.Count > 0) { var latestRelease = releases[0]; string version = latestRelease["tag_name"]?.ToString(); string releaseNotes = latestRelease["body"]?.ToString(); string downloadUrl = latestRelease["assets"]?.First?["browser_download_url"]?.ToString(); - + DateTime? releaseTime = null; if (latestRelease["published_at"] != null && DateTime.TryParse(latestRelease["published_at"].ToString(), out DateTime parsedTime)) { releaseTime = parsedTime; } - + if (!string.IsNullOrEmpty(version) && !string.IsNullOrEmpty(downloadUrl)) return (version, downloadUrl, releaseNotes, releaseTime); } diff --git a/Ink Canvas/Helpers/BaseUploadQueue.cs b/Ink Canvas/Helpers/BaseUploadQueue.cs index 27d306c9..452eb729 100644 --- a/Ink Canvas/Helpers/BaseUploadQueue.cs +++ b/Ink Canvas/Helpers/BaseUploadQueue.cs @@ -1,6 +1,5 @@ using Newtonsoft.Json; using System; -using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; @@ -204,14 +203,14 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + var queueData = new List(); // 将队列转换为可序列化的格式 foreach (var item in _uploadQueue) { cancellationToken.ThrowIfCancellationRequested(); - + queueData.Add(new UploadQueueItemData { FilePath = item.FilePath, @@ -322,7 +321,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + var filesToUpload = new List(); // 从队列中取出最多BATCH_SIZE个文件 @@ -330,7 +329,7 @@ namespace Ink_Canvas.Helpers while (count < BATCH_SIZE && _uploadQueue.TryDequeue(out UploadQueueItem item)) { cancellationToken.ThrowIfCancellationRequested(); - + // 再次检查文件是否存在 if (File.Exists(item.FilePath) && IsValidFile(item.FilePath)) { @@ -525,7 +524,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + // 检查是否启用 if (!IsUploadEnabled()) { diff --git a/Ink Canvas/Helpers/ComPPTLinkManager.cs b/Ink Canvas/Helpers/ComPPTLinkManager.cs index 9faa9f27..f8d3f432 100644 --- a/Ink Canvas/Helpers/ComPPTLinkManager.cs +++ b/Ink Canvas/Helpers/ComPPTLinkManager.cs @@ -1,5 +1,4 @@ using System; -using Microsoft.Office.Interop.PowerPoint; namespace Ink_Canvas.Helpers { diff --git a/Ink Canvas/Helpers/DlassApiClient.cs b/Ink Canvas/Helpers/DlassApiClient.cs index c39597c2..13f696cf 100644 --- a/Ink Canvas/Helpers/DlassApiClient.cs +++ b/Ink Canvas/Helpers/DlassApiClient.cs @@ -71,7 +71,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + var requestData = new { app_id = _appId, @@ -122,7 +122,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + string token = null; if (requireAuth) { @@ -185,7 +185,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + string token = null; if (requireAuth) { @@ -254,7 +254,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + string token = null; if (requireAuth) { @@ -323,7 +323,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + string token = null; if (requireAuth) { @@ -386,7 +386,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + if (!File.Exists(filePath)) { throw new FileNotFoundException($"文件不存在: {filePath}"); diff --git a/Ink Canvas/Helpers/DlassUploadQueue.cs b/Ink Canvas/Helpers/DlassUploadQueue.cs index 6f679d84..030c40d4 100644 --- a/Ink Canvas/Helpers/DlassUploadQueue.cs +++ b/Ink Canvas/Helpers/DlassUploadQueue.cs @@ -97,7 +97,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + // 再次检查文件是否存在(可能在队列等待时被删除) if (!File.Exists(filePath)) { @@ -148,7 +148,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + var uploadResult = await apiClient.UploadNoteAsync( "/api/whiteboard/upload_note", filePath, @@ -191,7 +191,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + var selectedClassName = MainWindow.Settings?.Dlass?.SelectedClassName; if (string.IsNullOrEmpty(selectedClassName)) { diff --git a/Ink Canvas/Helpers/IPPTLinkManager.cs b/Ink Canvas/Helpers/IPPTLinkManager.cs index 57ea84fe..79822f4b 100644 --- a/Ink Canvas/Helpers/IPPTLinkManager.cs +++ b/Ink Canvas/Helpers/IPPTLinkManager.cs @@ -1,5 +1,4 @@ using System; -using Microsoft.Office.Interop.PowerPoint; namespace Ink_Canvas.Helpers { diff --git a/Ink Canvas/Helpers/LocalizationHelper.cs b/Ink Canvas/Helpers/LocalizationHelper.cs index a0ebf82e..0890d0d0 100644 --- a/Ink Canvas/Helpers/LocalizationHelper.cs +++ b/Ink Canvas/Helpers/LocalizationHelper.cs @@ -1,6 +1,6 @@ +using Ink_Canvas.Properties; using System.Globalization; using System.Threading; -using Ink_Canvas.Properties; namespace Ink_Canvas.Helpers { diff --git a/Ink Canvas/Helpers/PPTInkManager.cs b/Ink Canvas/Helpers/PPTInkManager.cs index 19068454..1dbde920 100644 --- a/Ink Canvas/Helpers/PPTInkManager.cs +++ b/Ink Canvas/Helpers/PPTInkManager.cs @@ -2,8 +2,6 @@ using Microsoft.Office.Interop.PowerPoint; using System; using System.IO; using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; using System.Windows.Ink; namespace Ink_Canvas.Helpers @@ -455,7 +453,8 @@ namespace Ink_Canvas.Helpers { for (int i = 0; i < _memoryStreams.Length; i++) { - try { _memoryStreams[i]?.Dispose(); } catch (Exception ex) { LogHelper.WriteLogToFile($"释放内存流 {i} 失败: {ex}", LogHelper.LogType.Warning); } + try { _memoryStreams[i]?.Dispose(); } + catch (Exception ex) { LogHelper.WriteLogToFile($"释放内存流 {i} 失败: {ex}", LogHelper.LogType.Warning); } finally { _memoryStreams[i] = null; } } _memoryStreams = new MemoryStream[_maxSlides + 2]; @@ -544,7 +543,8 @@ namespace Ink_Canvas.Helpers if (_memoryStreams[i] != null) { long len = _memoryStreams[i].Length; - try { _memoryStreams[i].Dispose(); freed += len; cleaned++; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } + try { _memoryStreams[i].Dispose(); freed += len; cleaned++; } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } finally { _memoryStreams[i] = null; } } } diff --git a/Ink Canvas/Helpers/PPTManager.cs b/Ink Canvas/Helpers/PPTManager.cs index db161a79..2814cd64 100644 --- a/Ink Canvas/Helpers/PPTManager.cs +++ b/Ink Canvas/Helpers/PPTManager.cs @@ -66,7 +66,7 @@ namespace Ink_Canvas.Helpers private volatile bool _cachedIsInSlideShow; private readonly object _lockObject = new object(); private bool _disposed; - private static bool IsPptBusyHResult(uint hr) => hr == 0x80010001 || hr == 0x8001010A; + private static bool IsPptBusyHResult(uint hr) => hr == 0x80010001 || hr == 0x8001010A; #endregion #region Constructor & Initialization @@ -141,13 +141,13 @@ namespace Ink_Canvas.Helpers private void CheckAndConnectToPPT() { if (_isModuleUnloading) return; - + lock (_lockObject) { try { if (_isModuleUnloading) return; - + // 尝试连接到PowerPoint var pptApp = TryConnectToPowerPoint(); if (pptApp == null && IsSupportWPS) @@ -465,7 +465,7 @@ namespace Ink_Canvas.Helpers SafeReleaseComObject(CurrentSlide, "CurrentSlide"); SafeReleaseComObject(CurrentSlides, "CurrentSlides"); SafeReleaseComObject(CurrentPresentation, "CurrentPresentation"); - + if (PPTApplication != null && Marshal.IsComObject(PPTApplication)) { try @@ -518,13 +518,13 @@ namespace Ink_Canvas.Helpers _isModuleUnloading = false; return; } - + GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); - + Thread.Sleep(1000); - + _isModuleUnloading = false; try @@ -538,7 +538,7 @@ namespace Ink_Canvas.Helpers { LogHelper.WriteLogToFile("PPT联动模块重载时计时器已释放,跳过重启", LogHelper.LogType.Trace); } - + LogHelper.WriteLogToFile("PPT联动模块已重新加载", LogHelper.LogType.Trace); } catch (Exception ex) diff --git a/Ink Canvas/Helpers/PPTROTConnectionHelper.cs b/Ink Canvas/Helpers/PPTROTConnectionHelper.cs index b92751c3..a042ea0c 100644 --- a/Ink Canvas/Helpers/PPTROTConnectionHelper.cs +++ b/Ink Canvas/Helpers/PPTROTConnectionHelper.cs @@ -1,13 +1,10 @@ -using Microsoft.Office.Interop.PowerPoint; using System; using System.Collections.Generic; using System.Diagnostics; -using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; -using System.Threading; namespace Ink_Canvas.Helpers { @@ -426,21 +423,21 @@ namespace Ink_Canvas.Helpers if (fgPid == sswPid) return true; - try + try + { + using (Process fgProc = Process.GetProcessById((int)fgPid)) + using (Process appProc = Process.GetProcessById((int)sswPid)) { - using (Process fgProc = Process.GetProcessById((int)fgPid)) - using (Process appProc = Process.GetProcessById((int)sswPid)) - { - string fgName = fgProc.ProcessName.ToLower(); - string appName = appProc.ProcessName.ToLower(); + string fgName = fgProc.ProcessName.ToLower(); + string appName = appProc.ProcessName.ToLower(); - if (fgName.StartsWith("wps") && appName.StartsWith("wpp")) - { - return true; - } + if (fgName.StartsWith("wps") && appName.StartsWith("wpp")) + { + return true; } } - catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } + } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } return false; } diff --git a/Ink Canvas/Helpers/ProcessProtectionManager.cs b/Ink Canvas/Helpers/ProcessProtectionManager.cs index 33afe576..2e4a7ce6 100644 --- a/Ink Canvas/Helpers/ProcessProtectionManager.cs +++ b/Ink Canvas/Helpers/ProcessProtectionManager.cs @@ -2,7 +2,6 @@ using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Runtime.InteropServices; using System.Threading; diff --git a/Ink Canvas/Helpers/ROTPPTManager.cs b/Ink Canvas/Helpers/ROTPPTManager.cs index 96aa1ba6..7c044fb2 100644 --- a/Ink Canvas/Helpers/ROTPPTManager.cs +++ b/Ink Canvas/Helpers/ROTPPTManager.cs @@ -3,13 +3,10 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Timers; -using System.Windows.Threading; -using Application = System.Windows.Application; using Timer = System.Timers.Timer; namespace Ink_Canvas.Helpers @@ -74,7 +71,7 @@ namespace Ink_Canvas.Helpers slideShowWindows = PPTApplication.SlideShowWindows; if (slideShowWindows == null) return false; - + dynamic ssw = slideShowWindows; if (ssw.Count == 0) return false; @@ -86,7 +83,7 @@ namespace Ink_Canvas.Helpers dynamic sswObj = slideShowWindow; view = sswObj.View; if (view == null) return false; - + return true; } catch (COMException comEx) @@ -141,7 +138,7 @@ namespace Ink_Canvas.Helpers private bool _lastSlideShowState; private readonly object _lockObject = new object(); private bool _disposed; - + private dynamic _pptActivePresentation; private dynamic _pptSlideShowWindow; private int _polling = 0; @@ -183,7 +180,7 @@ namespace Ink_Canvas.Helpers lock (_monitoringLock) { _shouldStop = true; - + if (_monitoringThread != null && _monitoringThread.IsAlive) { // 等待线程退出,最多等待2秒 @@ -323,10 +320,10 @@ namespace Ink_Canvas.Helpers catch { LogHelper.WriteLogToFile("成功绑定!", LogHelper.LogType.Trace); - } - } - catch (Exception ex) - { + } + } + catch (Exception ex) + { LogHelper.WriteLogToFile($"绑定失败: {ex.Message}", LogHelper.LogType.Warning); DisconnectFromPPT(); } @@ -359,7 +356,7 @@ namespace Ink_Canvas.Helpers DisconnectFromPPT(); continue; } - + try { var _ = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(PPTApplication); @@ -371,7 +368,7 @@ namespace Ink_Canvas.Helpers DisconnectFromPPT(); continue; } - + activePresentation = PPTApplication.ActivePresentation; if (!PPTROTConnectionHelper.AreComObjectsEqual(_pptActivePresentation, activePresentation)) @@ -399,9 +396,9 @@ namespace Ink_Canvas.Helpers LogHelper.WriteLogToFile($"检查演示文稿状态COM异常: {comEx.Message} (HR: 0x{hr:X8})", LogHelper.LogType.Warning); DisconnectFromPPT(); continue; - } - catch (Exception ex) - { + } + catch (Exception ex) + { LogHelper.WriteLogToFile($"检查演示文稿状态失败: {ex.Message}", LogHelper.LogType.Warning); DisconnectFromPPT(); continue; @@ -429,7 +426,7 @@ namespace Ink_Canvas.Helpers isSlideShowActive = true; dynamic activeSlideShowWindow = null; - + try { for (int i = 1; i <= count; i++) @@ -467,7 +464,7 @@ namespace Ink_Canvas.Helpers bool isNewWindow = _pptSlideShowWindow == null; PPTROTConnectionHelper.SafeReleaseComObject(_pptSlideShowWindow); _pptSlideShowWindow = slideShowWindow; - + if (isNewWindow) { try @@ -482,7 +479,7 @@ namespace Ink_Canvas.Helpers } } } - + PPTROTConnectionHelper.SafeReleaseComObject(slideShowWindows); } else @@ -578,13 +575,13 @@ namespace Ink_Canvas.Helpers _updateTime = DateTime.Now; } - + if (_polling != 0) { try { int currentPage = GetCurrentSlideIndex(_pptSlideShowWindow); - + if (_lastPolledSlideNumber != -1 && currentPage != _lastPolledSlideNumber) { try @@ -596,7 +593,7 @@ namespace Ink_Canvas.Helpers LogHelper.WriteLogToFile($"触发轮询模式幻灯片切换事件失败: {ex.Message}", LogHelper.LogType.Warning); } } - + _lastPolledSlideNumber = currentPage; UpdateCurrentPresentationInfo(); _polling = 2; @@ -612,16 +609,16 @@ namespace Ink_Canvas.Helpers if (_lastSlideShowState) { LogHelper.WriteLogToFile("轮询检测到放映已结束", LogHelper.LogType.Trace); - + PPTROTConnectionHelper.SafeReleaseComObject(_pptSlideShowWindow); _pptSlideShowWindow = null; _lastPolledSlideNumber = -1; _polling = 1; SlidesCount = 0; - + _lastSlideShowState = false; SlideShowStateChanged?.Invoke(false); - + if (_pptActivePresentation != null) { try @@ -677,13 +674,13 @@ namespace Ink_Canvas.Helpers private void CheckAndConnectToPPT() { if (_isModuleUnloading) return; - + lock (_lockObject) { try { if (_isModuleUnloading) return; - + object bestApp = PPTROTConnectionHelper.GetAnyActivePowerPoint(PPTApplication, out int bestPriority, out int targetPriority); bool needRebind = false; @@ -704,7 +701,7 @@ namespace Ink_Canvas.Helpers if (needRebind) { LogHelper.WriteLogToFile($"需要重新绑定: bestPriority={bestPriority}, targetPriority={targetPriority}", LogHelper.LogType.Trace); - + bool wait = (PPTApplication != null); DisconnectFromPPT(); @@ -752,7 +749,7 @@ namespace Ink_Canvas.Helpers LogHelper.WriteLogToFile($"轮询模式:无法获取ActivePresentation: {ex.Message}", LogHelper.LogType.Trace); } } - + if (_pptActivePresentation != null) { CheckPresentationAndSlideShowState(); @@ -763,14 +760,14 @@ namespace Ink_Canvas.Helpers { // COM对象已失效,断开连接 LogHelper.WriteLogToFile("检测到COM对象失效,断开连接", LogHelper.LogType.Trace); - DisconnectFromPPT(); - } + DisconnectFromPPT(); + } catch (COMException comEx) - { + { // COM异常,记录并断开连接 var hr = (uint)comEx.HResult; LogHelper.WriteLogToFile($"PPT连接检查COM异常: {comEx.Message} (HR: 0x{hr:X8})", LogHelper.LogType.Warning); - DisconnectFromPPT(); + DisconnectFromPPT(); } catch (Exception ex) { @@ -792,7 +789,7 @@ namespace Ink_Canvas.Helpers { return; } - + try { var _ = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(PPTApplication); @@ -804,7 +801,7 @@ namespace Ink_Canvas.Helpers DisconnectFromPPT(); return; } - + dynamic activePresentation = null; dynamic slideShowWindow = null; @@ -838,9 +835,9 @@ namespace Ink_Canvas.Helpers LogHelper.WriteLogToFile($"检查演示文稿状态COM异常: {comEx.Message} (HR: 0x{hr:X8})", LogHelper.LogType.Warning); DisconnectFromPPT(); return; - } - catch (Exception ex) - { + } + catch (Exception ex) + { LogHelper.WriteLogToFile($"检查演示文稿状态失败: {ex.Message},继续使用轮询模式", LogHelper.LogType.Warning); activePresentation = null; } @@ -856,9 +853,9 @@ namespace Ink_Canvas.Helpers try { if (activePresentation == null) - { - try - { + { + try + { activePresentation = PPTApplication.ActivePresentation; } catch (Exception ex) @@ -924,7 +921,7 @@ namespace Ink_Canvas.Helpers if ((DateTime.Now - _updateTime).TotalMilliseconds > 3000 || _forcePolling) { LogHelper.WriteLogToFile($"轮询", LogHelper.LogType.Trace); - + try { dynamic pres = _pptActivePresentation; @@ -968,13 +965,13 @@ namespace Ink_Canvas.Helpers { LogHelper.WriteLogToFile($"轮询模式检测到页码变化: {_lastPolledSlideNumber} -> {currentPage},触发事件", LogHelper.LogType.Trace); SlideShowNextSlide?.Invoke(_pptSlideShowWindow); - } - catch (Exception ex) - { + } + catch (Exception ex) + { LogHelper.WriteLogToFile($"触发轮询模式幻灯片切换事件失败: {ex.Message}", LogHelper.LogType.Warning); } } - + _lastPolledSlideNumber = currentPage; } } @@ -1001,11 +998,11 @@ namespace Ink_Canvas.Helpers } if (_polling != 0) - { - try - { + { + try + { int currentPage = GetCurrentSlideIndex(_pptSlideShowWindow); - + if (_lastPolledSlideNumber != -1 && currentPage != _lastPolledSlideNumber) { try @@ -1018,7 +1015,7 @@ namespace Ink_Canvas.Helpers LogHelper.WriteLogToFile($"触发轮询模式幻灯片切换事件失败: {ex.Message}", LogHelper.LogType.Warning); } } - + _lastPolledSlideNumber = currentPage; UpdateCurrentPresentationInfo(); _polling = 2; @@ -1033,16 +1030,16 @@ namespace Ink_Canvas.Helpers if (_lastSlideShowState) { LogHelper.WriteLogToFile("轮询检测到放映已结束", LogHelper.LogType.Trace); - + PPTROTConnectionHelper.SafeReleaseComObject(_pptSlideShowWindow); _pptSlideShowWindow = null; _lastPolledSlideNumber = -1; _polling = 1; SlidesCount = 0; - + _lastSlideShowState = false; SlideShowStateChanged?.Invoke(false); - + if (_pptActivePresentation != null) { try @@ -1123,8 +1120,8 @@ namespace Ink_Canvas.Helpers try { if (pptApp != null) - { - PPTApplication = pptApp; + { + PPTApplication = pptApp; } try @@ -1200,7 +1197,7 @@ namespace Ink_Canvas.Helpers try { Microsoft.Office.Interop.PowerPoint.Application pptAppForEvents = PPTApplication as Microsoft.Office.Interop.PowerPoint.Application; - + if (pptAppForEvents != null) { pptAppForEvents.SlideShowNextSlide += new EApplication_SlideShowNextSlideEventHandler(OnSlideShowNextSlide); @@ -1218,7 +1215,7 @@ namespace Ink_Canvas.Helpers _bindingEvents = true; - LogHelper.WriteLogToFile("PPT事件注册成功", LogHelper.LogType.Trace); + LogHelper.WriteLogToFile("PPT事件注册成功", LogHelper.LogType.Trace); } else { @@ -1226,9 +1223,9 @@ namespace Ink_Canvas.Helpers _forcePolling = true; LogHelper.WriteLogToFile("无法转换为强类型Application,使用轮询模式", LogHelper.LogType.Trace); } - } - catch (Exception ex) - { + } + catch (Exception ex) + { _bindingEvents = false; _forcePolling = true; LogHelper.WriteLogToFile($"事件注册失败: {ex.Message},使用轮询模式", LogHelper.LogType.Trace); @@ -1252,10 +1249,10 @@ namespace Ink_Canvas.Helpers if (_pptActivePresentation != null) { - UpdateCurrentPresentationInfo(); + UpdateCurrentPresentationInfo(); } - PPTConnectionChanged?.Invoke(true); + PPTConnectionChanged?.Invoke(true); try { @@ -1327,7 +1324,7 @@ namespace Ink_Canvas.Helpers try { Microsoft.Office.Interop.PowerPoint.Application app = PPTApplication as Microsoft.Office.Interop.PowerPoint.Application; - + if (app != null) { app.SlideShowNextSlide -= new EApplication_SlideShowNextSlideEventHandler(OnSlideShowNextSlide); @@ -1335,9 +1332,9 @@ namespace Ink_Canvas.Helpers app.SlideShowEnd -= new EApplication_SlideShowEndEventHandler(OnSlideShowEndForComEvent); app.PresentationBeforeClose -= new EApplication_PresentationBeforeCloseEventHandler(OnPresentationBeforeClose); } - } - catch (Exception ex) - { + } + catch (Exception ex) + { LogHelper.WriteLogToFile($"取消PPT事件注册失败: {ex.Message}", LogHelper.LogType.Trace); } @@ -1530,7 +1527,7 @@ namespace Ink_Canvas.Helpers object view = null; object selection = null; object slideRange = null; - + try { if (PPTApplication != null && Marshal.IsComObject(PPTApplication)) @@ -1560,7 +1557,7 @@ namespace Ink_Canvas.Helpers CurrentSlides = null; return; } - + dynamic pres = _pptActivePresentation; CurrentPresentation = pres; CurrentSlides = pres.Slides; @@ -1581,28 +1578,28 @@ namespace Ink_Canvas.Helpers if (CurrentSlides != null) { - try - { - var slideCount = CurrentSlides.Count; - if (slideCount > 0) + try { - SlidesCount = slideCount; + var slideCount = CurrentSlides.Count; + if (slideCount > 0) + { + SlidesCount = slideCount; + } + else + { + SlidesCount = 0; + LogHelper.WriteLogToFile("PPT演示文稿页数为0,可能为空演示文稿", LogHelper.LogType.Warning); + } } - else + catch (COMException comEx) { + var hr = (uint)comEx.HResult; SlidesCount = 0; - LogHelper.WriteLogToFile("PPT演示文稿页数为0,可能为空演示文稿", LogHelper.LogType.Warning); + LogHelper.WriteLogToFile($"读取PPT页数失败: {comEx.Message} (HR: 0x{hr:X8})", LogHelper.LogType.Warning); } - } - catch (COMException comEx) - { - var hr = (uint)comEx.HResult; - SlidesCount = 0; - LogHelper.WriteLogToFile($"读取PPT页数失败: {comEx.Message} (HR: 0x{hr:X8})", LogHelper.LogType.Warning); - } - try - { + try + { if (IsInSlideShow && _pptSlideShowWindow != null) { try @@ -1618,57 +1615,57 @@ namespace Ink_Canvas.Helpers catch (Exception ex) { LogHelper.WriteLogToFile($"获取SlideShowWindow的Slide失败: {ex.Message}", LogHelper.LogType.Trace); + } } - } - else - { - activeWindow = PPTApplication.ActiveWindow; - if (activeWindow != null) + else { - dynamic aw = activeWindow; - selection = aw.Selection; - if (selection != null) + activeWindow = PPTApplication.ActiveWindow; + if (activeWindow != null) { - dynamic sel = selection; - slideRange = sel.SlideRange; - if (slideRange != null) + dynamic aw = activeWindow; + selection = aw.Selection; + if (selection != null) { - dynamic sr = slideRange; - int slideNumber = sr.SlideNumber; - if (slideNumber > 0 && slideNumber <= SlidesCount) + dynamic sel = selection; + slideRange = sel.SlideRange; + if (slideRange != null) { - CurrentSlide = CurrentSlides[slideNumber]; + dynamic sr = slideRange; + int slideNumber = sr.SlideNumber; + if (slideNumber > 0 && slideNumber <= SlidesCount) + { + CurrentSlide = CurrentSlides[slideNumber]; + } } } } + + if (CurrentSlide == null && SlidesCount > 0) + { + CurrentSlide = CurrentSlides[1]; + } } - - if (CurrentSlide == null && SlidesCount > 0) + } + catch (COMException comEx) + { + var hr = (uint)comEx.HResult; + if (hr != 0x8001010E && hr != 0x80004005) + { + LogHelper.WriteLogToFile($"获取当前幻灯片失败: {comEx.Message}", LogHelper.LogType.Warning); + } + + if (SlidesCount > 0) { CurrentSlide = CurrentSlides[1]; } } } - catch (COMException comEx) + else { - var hr = (uint)comEx.HResult; - if (hr != 0x8001010E && hr != 0x80004005) - { - LogHelper.WriteLogToFile($"获取当前幻灯片失败: {comEx.Message}", LogHelper.LogType.Warning); - } - - if (SlidesCount > 0) - { - CurrentSlide = CurrentSlides[1]; - } - } - } - else - { - CurrentPresentation = null; - CurrentSlides = null; - CurrentSlide = null; - SlidesCount = 0; + CurrentPresentation = null; + CurrentSlides = null; + CurrentSlide = null; + SlidesCount = 0; } } } @@ -1758,7 +1755,7 @@ namespace Ink_Canvas.Helpers try { Microsoft.Office.Interop.PowerPoint.Application app = PPTApplication as Microsoft.Office.Interop.PowerPoint.Application; - + if (app != null) { app.SlideShowNextSlide -= new EApplication_SlideShowNextSlideEventHandler(OnSlideShowNextSlide); @@ -1797,10 +1794,10 @@ namespace Ink_Canvas.Helpers { int currentPage = GetCurrentSlideIndex(_pptSlideShowWindow); int totalPage = GetTotalSlideIndex(_pptActivePresentation); - + if (currentPage >= totalPage) _polling = 1; else _polling = 0; - + SlidesCount = totalPage; _lastPolledSlideNumber = currentPage; // 初始化页码跟踪 } @@ -1839,10 +1836,10 @@ namespace Ink_Canvas.Helpers { int currentPage = GetCurrentSlideIndex(_pptSlideShowWindow); int totalPage = GetTotalSlideIndex(_pptActivePresentation); - + if (currentPage >= totalPage) _polling = 1; else _polling = 0; - + _lastPolledSlideNumber = currentPage; // 更新页码跟踪 } } @@ -2000,46 +1997,46 @@ namespace Ink_Canvas.Helpers try { object slideShowWindows = PPTApplication.SlideShowWindows; - if (slideShowWindows != null) - { - dynamic ssw = slideShowWindows; + if (slideShowWindows != null) + { + dynamic ssw = slideShowWindows; object slideShowWindow = ssw[1]; - if (slideShowWindow != null) - { - dynamic sswObj = slideShowWindow; + if (slideShowWindow != null) + { + dynamic sswObj = slideShowWindow; try { - sswObj.Activate(); + sswObj.Activate(); } catch { } try { object view = sswObj.View; - if (view != null) - { - dynamic viewObj = view; - viewObj.Next(); - } - } + if (view != null) + { + dynamic viewObj = view; + viewObj.Next(); + } + } catch { } SafeReleaseComObject(slideShowWindow); - } + } SafeReleaseComObject(slideShowWindows); } - } - catch (COMException comEx) - { - var hr = (uint)comEx.HResult; - if (hr == 0x8001010E || hr == 0x80004005) - { - DisconnectFromPPT(); - } - LogHelper.WriteLogToFile($"切换到下一页失败: {comEx.Message}", LogHelper.LogType.Error); - } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"切换到下一页失败: {ex}", LogHelper.LogType.Error); - } + } + catch (COMException comEx) + { + var hr = (uint)comEx.HResult; + if (hr == 0x8001010E || hr == 0x80004005) + { + DisconnectFromPPT(); + } + LogHelper.WriteLogToFile($"切换到下一页失败: {comEx.Message}", LogHelper.LogType.Error); + } + catch (Exception ex) + { + LogHelper.WriteLogToFile($"切换到下一页失败: {ex}", LogHelper.LogType.Error); + } }).Start(); return true; } @@ -2063,46 +2060,46 @@ namespace Ink_Canvas.Helpers try { object slideShowWindows = PPTApplication.SlideShowWindows; - if (slideShowWindows != null) - { - dynamic ssw = slideShowWindows; + if (slideShowWindows != null) + { + dynamic ssw = slideShowWindows; object slideShowWindow = ssw[1]; - if (slideShowWindow != null) - { - dynamic sswObj = slideShowWindow; + if (slideShowWindow != null) + { + dynamic sswObj = slideShowWindow; try { - sswObj.Activate(); + sswObj.Activate(); } catch { } try { object view = sswObj.View; - if (view != null) - { - dynamic viewObj = view; - viewObj.Previous(); - } - } + if (view != null) + { + dynamic viewObj = view; + viewObj.Previous(); + } + } catch { } SafeReleaseComObject(slideShowWindow); - } + } SafeReleaseComObject(slideShowWindows); } - } - catch (COMException comEx) - { - var hr = (uint)comEx.HResult; - if (hr == 0x8001010E || hr == 0x80004005) - { - DisconnectFromPPT(); - } - LogHelper.WriteLogToFile($"切换到上一页失败: {comEx.Message}", LogHelper.LogType.Error); - } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"切换到上一页失败: {ex}", LogHelper.LogType.Error); - } + } + catch (COMException comEx) + { + var hr = (uint)comEx.HResult; + if (hr == 0x8001010E || hr == 0x80004005) + { + DisconnectFromPPT(); + } + LogHelper.WriteLogToFile($"切换到上一页失败: {comEx.Message}", LogHelper.LogType.Error); + } + catch (Exception ex) + { + LogHelper.WriteLogToFile($"切换到上一页失败: {ex}", LogHelper.LogType.Error); + } }).Start(); return true; } @@ -2308,13 +2305,13 @@ namespace Ink_Canvas.Helpers try { if (slideShowWindow == null) return 0; - + // 检查COM对象是否有效 if (!Marshal.IsComObject(slideShowWindow)) { return 0; } - + try { var _ = Marshal.GetIUnknownForObject(slideShowWindow); @@ -2324,12 +2321,12 @@ namespace Ink_Canvas.Helpers { return 0; } - + dynamic ssw = slideShowWindow; view = ssw.View; - if (view != null) - { - dynamic viewObj = view; + if (view != null) + { + dynamic viewObj = view; slide = viewObj.Slide; if (slide != null) { @@ -2885,8 +2882,8 @@ namespace Ink_Canvas.Helpers try { Marshal.ReleaseComObject(PPTApplication); - PPTApplication = null; - LogHelper.WriteLogToFile("已释放pptApp对象", LogHelper.LogType.Trace); + PPTApplication = null; + LogHelper.WriteLogToFile("已释放pptApp对象", LogHelper.LogType.Trace); } catch (Exception ex) { @@ -3369,7 +3366,7 @@ namespace Ink_Canvas.Helpers try { // 尝试强类型转换 - Microsoft.Office.Interop.PowerPoint.SlideShowWindow slideWindow = + Microsoft.Office.Interop.PowerPoint.SlideShowWindow slideWindow = pptSlideShowWindowObj as Microsoft.Office.Interop.PowerPoint.SlideShowWindow; if (slideWindow != null) diff --git a/Ink Canvas/Helpers/SecurityManager.cs b/Ink Canvas/Helpers/SecurityManager.cs index 35ad8fcd..c24bf4ca 100644 --- a/Ink Canvas/Helpers/SecurityManager.cs +++ b/Ink Canvas/Helpers/SecurityManager.cs @@ -1,12 +1,10 @@ +using iNKORE.UI.WPF.Modern.Controls; using System; using System.Security.Cryptography; -using System.Text; +using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; -using Ink_Canvas.Windows; -using iNKORE.UI.WPF.Modern.Controls; -using MessageBox=iNKORE.UI.WPF.Modern.Controls.MessageBox; -using System.Threading.Tasks; +using MessageBox = iNKORE.UI.WPF.Modern.Controls.MessageBox; namespace Ink_Canvas.Helpers { diff --git a/Ink Canvas/Helpers/TelemetryUploader.cs b/Ink Canvas/Helpers/TelemetryUploader.cs index a398f121..025b2466 100644 --- a/Ink Canvas/Helpers/TelemetryUploader.cs +++ b/Ink Canvas/Helpers/TelemetryUploader.cs @@ -1,10 +1,9 @@ +using Sentry; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading.Tasks; -using Sentry; -using Sentry.Protocol; namespace Ink_Canvas.Helpers { @@ -122,7 +121,7 @@ namespace Ink_Canvas.Helpers { Id = deviceId, Username = userName, - Email = $"{userName}", + Email = $"{userName}", IpAddress = "{{auto}}" }; }); @@ -137,7 +136,7 @@ namespace Ink_Canvas.Helpers { Id = deviceId, Username = userName, - Email = $"{userName}", + Email = $"{userName}", IpAddress = "{{auto}}" }; @@ -146,7 +145,7 @@ namespace Ink_Canvas.Helpers evt.SetTag("update_channel", settings.Startup.UpdateChannel.ToString()); evt.SetTag("app_version", Assembly.GetExecutingAssembly().GetName().Version.ToString()); evt.SetTag("os_version", Environment.OSVersion.VersionString); - evt.SetExtra("telemetry_data", telemetryData); + evt.SetExtra("telemetry_data", telemetryData); if (crashFiles != null) { diff --git a/Ink Canvas/Helpers/UploadHelper.cs b/Ink Canvas/Helpers/UploadHelper.cs index 13a0e7bf..dbc417f4 100644 --- a/Ink Canvas/Helpers/UploadHelper.cs +++ b/Ink Canvas/Helpers/UploadHelper.cs @@ -2,8 +2,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Threading.Tasks; using System.Threading; +using System.Threading.Tasks; namespace Ink_Canvas.Helpers { diff --git a/Ink Canvas/Helpers/UploadQueueHelper.cs b/Ink Canvas/Helpers/UploadQueueHelper.cs index d08efd46..4105f590 100644 --- a/Ink Canvas/Helpers/UploadQueueHelper.cs +++ b/Ink Canvas/Helpers/UploadQueueHelper.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; namespace Ink_Canvas.Helpers { diff --git a/Ink Canvas/Helpers/UriSchemeHelper.cs b/Ink Canvas/Helpers/UriSchemeHelper.cs index 1e957402..47f5ce09 100644 --- a/Ink Canvas/Helpers/UriSchemeHelper.cs +++ b/Ink Canvas/Helpers/UriSchemeHelper.cs @@ -1,7 +1,6 @@ using Microsoft.Win32; using System; using System.Diagnostics; -using System.Security; namespace Ink_Canvas.Helpers { diff --git a/Ink Canvas/Helpers/WebDavUploadQueue.cs b/Ink Canvas/Helpers/WebDavUploadQueue.cs index 82bbf567..395c099b 100644 --- a/Ink Canvas/Helpers/WebDavUploadQueue.cs +++ b/Ink Canvas/Helpers/WebDavUploadQueue.cs @@ -31,7 +31,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + // 再次检查文件是否存在(可能在队列等待时被删除) if (!File.Exists(filePath)) { diff --git a/Ink Canvas/Helpers/WebDavUploader.cs b/Ink Canvas/Helpers/WebDavUploader.cs index 7c229688..935c59d2 100644 --- a/Ink Canvas/Helpers/WebDavUploader.cs +++ b/Ink Canvas/Helpers/WebDavUploader.cs @@ -23,7 +23,7 @@ namespace Ink_Canvas.Helpers try { cancellationToken.ThrowIfCancellationRequested(); - + // 检查文件是否存在 if (!File.Exists(filePath)) { @@ -66,7 +66,7 @@ namespace Ink_Canvas.Helpers { // 检查取消令牌 cancellationToken.ThrowIfCancellationRequested(); - + var result = await client.PutFile(targetPath, fileStream); if (result.IsSuccessful) { @@ -79,7 +79,7 @@ namespace Ink_Canvas.Helpers if (!string.IsNullOrEmpty(directoryPath)) { await EnsureDirectoryExistsAsync(client, directoryPath, cancellationToken); - + // 再次尝试上传文件 cancellationToken.ThrowIfCancellationRequested(); using (var retryStream = File.OpenRead(filePath)) @@ -132,7 +132,7 @@ namespace Ink_Canvas.Helpers // 检查取消令牌 cancellationToken.ThrowIfCancellationRequested(); - + // 尝试创建目录 await client.Mkcol(currentPath); } diff --git a/Ink Canvas/Helpers/WindowOverviewModel.cs b/Ink Canvas/Helpers/WindowOverviewModel.cs index a8f505f6..e3c14e49 100644 --- a/Ink Canvas/Helpers/WindowOverviewModel.cs +++ b/Ink Canvas/Helpers/WindowOverviewModel.cs @@ -5,8 +5,6 @@ using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; -using System.Threading.Tasks; -using System.Windows; namespace Ink_Canvas.Helpers { @@ -137,15 +135,15 @@ namespace Ink_Canvas.Helpers private Timer _updateTimer; private bool _isDisposed = false; private readonly int _updateInterval = 1000; // 更新间隔(毫秒) - + private readonly Dictionary _processCache = new Dictionary(); private readonly object _processCacheLock = new object(); private DateTime _lastProcessCacheCleanup = DateTime.Now; - private const int PROCESS_CACHE_CLEANUP_INTERVAL_MS = 30000; - + private const int PROCESS_CACHE_CLEANUP_INTERVAL_MS = 30000; + // 窗口缓存,用于增量更新 private readonly Dictionary _windowCache = new Dictionary(); - + /// /// 进程缓存信息 /// @@ -219,26 +217,26 @@ namespace Ink_Canvas.Helpers .Where(kvp => (now - kvp.Value.LastAccessTime).TotalMilliseconds > PROCESS_CACHE_CLEANUP_INTERVAL_MS) .Select(kvp => kvp.Key) .ToList(); - + foreach (var key in keysToRemove) { _processCache.Remove(key); } - + _lastProcessCacheCleanup = now; } - + // 检查缓存 if (_processCache.TryGetValue(processId, out var cachedInfo)) { cachedInfo.LastAccessTime = now; return (cachedInfo.ProcessName, cachedInfo.ProcessPath); } - + // 缓存未命中,获取进程信息 string processName = "Unknown"; string processPath = "Unknown"; - + try { Process process = Process.GetProcessById((int)processId); @@ -256,7 +254,7 @@ namespace Ink_Canvas.Helpers { // 进程可能已退出 } - + // 添加到缓存 _processCache[processId] = new ProcessCacheInfo { @@ -264,11 +262,11 @@ namespace Ink_Canvas.Helpers ProcessPath = processPath, LastAccessTime = now }; - + return (processName, processPath); } } - + /// /// 检查窗口信息是否发生变化 /// @@ -278,7 +276,7 @@ namespace Ink_Canvas.Helpers { return true; // 新窗口 } - + // 检查关键属性是否变化 return cachedWindow.Rect.Left != rect.Left || cachedWindow.Rect.Top != rect.Top || @@ -338,10 +336,10 @@ namespace Ink_Canvas.Helpers // 检查窗口是否发生变化 bool windowChanged = HasWindowChanged(hWnd, rect, isMinimized, isMaximized, isFullScreen); - + // 获取进程信息 GetWindowThreadProcessId(hWnd, out uint processId); - + // 使用缓存的进程信息 var (processName, processPath) = GetProcessInfo(processId); @@ -371,7 +369,7 @@ namespace Ink_Canvas.Helpers ProcessId = processId, IsFullScreen = isFullScreen }; - + // 更新缓存以保持ZOrder等属性最新 _windowCache[hWnd] = windowInfo; } @@ -404,7 +402,7 @@ namespace Ink_Canvas.Helpers ProcessId = processId, IsFullScreen = isFullScreen }; - + // 更新缓存 _windowCache[hWnd] = windowInfo; } @@ -600,12 +598,12 @@ namespace Ink_Canvas.Helpers { _windows.Clear(); } - + lock (_processCacheLock) { _processCache.Clear(); } - + _windowCache.Clear(); } } diff --git a/Ink Canvas/MainWindow.xaml.cs b/Ink Canvas/MainWindow.xaml.cs index 5da3bf16..9fe9278b 100644 --- a/Ink Canvas/MainWindow.xaml.cs +++ b/Ink Canvas/MainWindow.xaml.cs @@ -239,7 +239,7 @@ namespace Ink_Canvas ShowPage(currentPageIndex); // 手动实现触摸滑动 - const double TouchTapMovementThreshold = 15.0; + const double TouchTapMovementThreshold = 15.0; double leftTouchStartY = 0; double leftTouchStartX = 0; double leftScrollStartOffset = 0; @@ -849,7 +849,7 @@ namespace Ink_Canvas if (drawingAttributes == null) drawingAttributes = inkCanvas.DefaultDrawingAttributes; - if (penType == 1) return; + if (penType == 1) return; if (_isBoardBrushMode) { @@ -1066,7 +1066,7 @@ namespace Ink_Canvas } else { - width = sliderValue / 2.0; + width = sliderValue / 2.0; } SetBrushAttributesDirectly(targetColor, width, width); @@ -1373,7 +1373,7 @@ namespace Ink_Canvas // 初始化UIA置顶开关 ToggleSwitchUIAccessTopMost.IsOn = Settings.Advanced.EnableUIAccessTopMost; UpdateUIAccessTopMostVisibility(); - + App.IsUIAccessTopMostEnabled = Settings.Advanced.EnableUIAccessTopMost; // 初始化橡皮擦自动切换回批注模式开关 @@ -1439,7 +1439,7 @@ namespace Ink_Canvas if (TimerControl != null && MinimizedTimerControl != null) { MinimizedTimerControl.SetParentControl(TimerControl); - + // 设置PPT时间胶囊的父控件 if (PPTTimeCapsule != null) { @@ -1451,9 +1451,9 @@ namespace Ink_Canvas if (TimerContainer != null && MinimizedTimerContainer != null && MinimizedTimerControl != null) { TimerContainer.Visibility = Visibility.Collapsed; - - if (Settings.PowerPointSettings.EnablePPTTimeCapsule && - BtnPPTSlideShowEnd.Visibility == Visibility.Visible && + + if (Settings.PowerPointSettings.EnablePPTTimeCapsule && + BtnPPTSlideShowEnd.Visibility == Visibility.Visible && PPTTimeCapsule != null) { MinimizedTimerContainer.Visibility = Visibility.Collapsed; @@ -1473,20 +1473,20 @@ namespace Ink_Canvas MinimizedTimerContainer.Visibility = Visibility.Collapsed; MinimizedTimerControl.Visibility = Visibility.Collapsed; } - + // 如果启用了PPT时间胶囊,停止倒计时显示 if (Settings.PowerPointSettings.EnablePPTTimeCapsule && PPTTimeCapsule != null) { PPTTimeCapsule.StopCountdown(); } }; - + // 监听计时器完成事件 TimerControl.TimerCompleted += (s, args) => { // 如果启用了PPT时间胶囊且在PPT模式下,触发完成动画 - if (Settings.PowerPointSettings.EnablePPTTimeCapsule && - BtnPPTSlideShowEnd.Visibility == Visibility.Visible && + if (Settings.PowerPointSettings.EnablePPTTimeCapsule && + BtnPPTSlideShowEnd.Visibility == Visibility.Visible && PPTTimeCapsule != null) { PPTTimeCapsule.OnTimerCompleted(); @@ -2286,7 +2286,7 @@ namespace Ink_Canvas try { // 检查是否在橡皮擦模式且启用了自动切换功能 - if ((inkCanvas.EditingMode == InkCanvasEditingMode.EraseByPoint || + if ((inkCanvas.EditingMode == InkCanvasEditingMode.EraseByPoint || inkCanvas.EditingMode == InkCanvasEditingMode.EraseByStroke) && Settings.Canvas.EnableEraserAutoSwitchBack) { @@ -3935,7 +3935,7 @@ namespace Ink_Canvas { if (PPTTimeCapsuleContainer == null || PPTTimeCapsule == null) return; - if (Settings.PowerPointSettings.EnablePPTTimeCapsule && + if (Settings.PowerPointSettings.EnablePPTTimeCapsule && BtnPPTSlideShowEnd.Visibility == Visibility.Visible) { PPTTimeCapsuleContainer.Visibility = Visibility.Visible; diff --git a/Ink Canvas/MainWindow_cs/MW_AutoFold.cs b/Ink Canvas/MainWindow_cs/MW_AutoFold.cs index 1432a843..4a3934be 100644 --- a/Ink Canvas/MainWindow_cs/MW_AutoFold.cs +++ b/Ink Canvas/MainWindow_cs/MW_AutoFold.cs @@ -17,7 +17,7 @@ namespace Ink_Canvas /// 浮动栏是否折叠的标志。 /// public bool isFloatingBarFolded; - + /// /// 浮动栏正在改变隐藏模式的标志,用于防止重复操作。 /// @@ -100,7 +100,7 @@ namespace Ink_Canvas if (sender == Fold_Icon && lastBorderMouseDownObject != Fold_Icon) isShouldRejectAction = true; }); - if (isShouldRejectAction) + if (isShouldRejectAction) { return; } @@ -114,7 +114,7 @@ namespace Ink_Canvas if (isFloatingBarFolded) return; - if (isFloatingBarChangingHideMode) + if (isFloatingBarChangingHideMode) { return; } @@ -384,12 +384,12 @@ namespace Ink_Canvas unfoldFloatingBarByUser = true; foldFloatingBarByUser = false; - if (isFloatingBarChangingHideMode) + if (isFloatingBarChangingHideMode) { return; } - + await Dispatcher.InvokeAsync(() => { isFloatingBarChangingHideMode = true; diff --git a/Ink Canvas/MainWindow_cs/MW_BoardControls.cs b/Ink Canvas/MainWindow_cs/MW_BoardControls.cs index b9b58932..c8ea6c80 100644 --- a/Ink Canvas/MainWindow_cs/MW_BoardControls.cs +++ b/Ink Canvas/MainWindow_cs/MW_BoardControls.cs @@ -1,7 +1,6 @@ using Ink_Canvas.Helpers; using System; using System.Collections.Generic; -using System.Diagnostics; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; @@ -236,8 +235,8 @@ namespace Ink_Canvas var elementsToProcess = new List(); foreach (var item in TimeMachineHistories[0]) { - if (item.CommitType == TimeMachineHistoryType.ElementInsert && - !item.StrokeHasBeenCleared && + if (item.CommitType == TimeMachineHistoryType.ElementInsert && + !item.StrokeHasBeenCleared && item.InsertedElement != null && !removed0.Contains(item.InsertedElement)) { @@ -255,8 +254,8 @@ namespace Ink_Canvas var elementsToProcess = new List(); foreach (var item in TimeMachineHistories[CurrentWhiteboardIndex]) { - if (item.CommitType == TimeMachineHistoryType.ElementInsert && - !item.StrokeHasBeenCleared && + if (item.CommitType == TimeMachineHistoryType.ElementInsert && + !item.StrokeHasBeenCleared && item.InsertedElement != null && !removed.Contains(item.InsertedElement)) { diff --git a/Ink Canvas/MainWindow_cs/MW_ClipboardHandler.cs b/Ink Canvas/MainWindow_cs/MW_ClipboardHandler.cs index 2d78f910..08ac78ec 100644 --- a/Ink Canvas/MainWindow_cs/MW_ClipboardHandler.cs +++ b/Ink Canvas/MainWindow_cs/MW_ClipboardHandler.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; -using System.Windows.Forms; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Interop; diff --git a/Ink Canvas/MainWindow_cs/MW_FloatingBarIcons.cs b/Ink Canvas/MainWindow_cs/MW_FloatingBarIcons.cs index d720f600..3744d19f 100644 --- a/Ink Canvas/MainWindow_cs/MW_FloatingBarIcons.cs +++ b/Ink Canvas/MainWindow_cs/MW_FloatingBarIcons.cs @@ -1161,10 +1161,10 @@ namespace Ink_Canvas { // 每次打开计时器窗口时重置计时器 TimerControl.ResetTimerState(); - + // 根据DPI缩放因子调整TimerContainer的尺寸 AdjustTimerContainerSize(); - + TimerContainer.Visibility = Visibility.Visible; if (MinimizedTimerContainer != null) { diff --git a/Ink Canvas/MainWindow_cs/MW_PPT.cs b/Ink Canvas/MainWindow_cs/MW_PPT.cs index f6e70aab..0e7982c0 100644 --- a/Ink Canvas/MainWindow_cs/MW_PPT.cs +++ b/Ink Canvas/MainWindow_cs/MW_PPT.cs @@ -73,22 +73,22 @@ namespace Ink_Canvas /// PowerPoint应用程序实例,用于与PowerPoint进行交互。 /// public static Microsoft.Office.Interop.PowerPoint.Application pptApplication; - + /// /// 当前活动的PowerPoint演示文稿。 /// public static Presentation presentation; - + /// /// 当前演示文稿的幻灯片集合。 /// public static Slides slides; - + /// /// 当前活动的幻灯片。 /// public static Slide slide; - + /// /// 当前演示文稿的幻灯片总数。 /// @@ -99,8 +99,8 @@ namespace Ink_Canvas /// /// 幻灯片放映结束事件重入保护标志,防止重复处理放映结束事件。 /// - private bool isEnteredSlideShowEndEvent; - + private bool isEnteredSlideShowEndEvent; + /// /// 演示文稿是否有黑边的指示标志。 /// @@ -111,17 +111,17 @@ namespace Ink_Canvas /// 用于处理长按翻页功能的定时器。 /// private DispatcherTimer _longPressTimer; - + /// /// 长按翻页方向标志,true表示下一页,false表示上一页。 /// private bool _isLongPressNext = true; // true为下一页,false为上一页 - + /// /// 长按延迟时间(毫秒),即用户需要按住按钮多长时间才开始连续翻页。 /// private const int LongPressDelay = 500; // 长按延迟时间(毫秒) - + /// /// 长按翻页间隔(毫秒),即连续翻页的时间间隔。 /// @@ -132,7 +132,7 @@ namespace Ink_Canvas /// 用于监控PowerPoint应用程序状态的定时器。 /// private DispatcherTimer _powerPointProcessMonitorTimer; - + /// /// 应用程序监控间隔(毫秒),即每隔多长时间检查一次PowerPoint应用程序状态。 /// @@ -143,12 +143,12 @@ namespace Ink_Canvas /// 上次播放的幻灯片页码。 /// private int _lastPlaybackPage = 0; - + /// /// 是否应该导航到上次播放页码的标志。 /// private bool _shouldNavigateToLastPage = false; - + // 当前播放页码跟踪 /// /// 当前幻灯片放映的位置(页码)。 @@ -162,11 +162,11 @@ namespace Ink_Canvas /// 用于在PowerPoint连接断开后延迟退出PPT模式的定时器。 /// private DispatcherTimer _exitPPTModeAfterDisconnectTimer; - + /// /// 断开连接后退出PPT模式的延迟时间(毫秒),即连接断开后多长时间才退出PPT模式。 /// - private const int ExitPPTModeAfterDisconnectDelayMs = 1200; + private const int ExitPPTModeAfterDisconnectDelayMs = 1200; #endregion #region PPT Managers @@ -174,12 +174,12 @@ namespace Ink_Canvas /// PPT链接管理器,用于管理与PowerPoint的连接和事件处理。 /// private IPPTLinkManager _pptManager; - + /// /// PPT墨迹管理器,用于管理PowerPoint幻灯片上的墨迹。 /// private PPTInkManager _singlePPTInkManager; - + /// /// PPT UI管理器,用于管理与PowerPoint相关的用户界面元素。 /// @@ -1432,7 +1432,7 @@ namespace Ink_Canvas if (GridTransparencyFakeBackground.Background != Brushes.Transparent) BtnHideInkCanvas_Click(BtnHideInkCanvas, null); SetCurrentToolMode(InkCanvasEditingMode.None); - + UpdateCurrentToolMode("cursor"); SetFloatingBarHighlightPosition("cursor"); } @@ -1785,7 +1785,7 @@ namespace Ink_Canvas // 重置上次播放位置相关字段 _lastPlaybackPage = 0; _shouldNavigateToLastPage = false; - + // 重置当前播放页码跟踪 _currentSlideShowPosition = 0; _previousSlideID = 0; @@ -1922,7 +1922,7 @@ namespace Ink_Canvas { Settings.PowerPointSettings.PowerPointSupport = true; ToggleSwitchSupportPowerPoint.IsOn = true; - + // 启动PPT监控 if (_pptManager == null) { @@ -1973,7 +1973,7 @@ namespace Ink_Canvas /// 指示是否正在显示恢复隐藏幻灯片的窗口 /// public static bool IsShowingRestoreHiddenSlidesWindow; - + /// /// 指示是否正在显示自动播放提示窗口 /// @@ -2305,7 +2305,7 @@ namespace Ink_Canvas { PureViewboxFloatingBarMarginAnimationInDesktopMode(); if (Settings.Automation.IsAutoEnterAnnotationModeWhenExitFoldMode) - { + { await Task.Delay(350); if (!isFloatingBarFolded) { diff --git a/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs b/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs index 61aa33d0..e55d8e15 100644 --- a/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs +++ b/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs @@ -147,7 +147,7 @@ namespace Ink_Canvas { // 检查是否是PPT模式 bool isPPTMode = BtnPPTSlideShowEnd.Visibility == Visibility.Visible && _pptManager?.IsConnected == true; - + if (isPPTMode) { // PPT模式:保存为多个XML文件 @@ -593,22 +593,22 @@ namespace Ink_Canvas } // 创建ZIP文件 - if (File.Exists(zipFileName)) - File.Delete(zipFileName); + if (File.Exists(zipFileName)) + File.Delete(zipFileName); - ZipFile.CreateFromDirectory(tempDir, zipFileName); + ZipFile.CreateFromDirectory(tempDir, zipFileName); - // 异步上传ZIP文件到Dlass - _ = Task.Run(async () => - { - try + // 异步上传ZIP文件到Dlass + _ = Task.Run(async () => { - await Helpers.UploadHelper.UploadFileAsync(zipFileName); - } - catch (Exception) - { - } - }); + try + { + await Helpers.UploadHelper.UploadFileAsync(zipFileName); + } + catch (Exception) + { + } + }); if (newNotice) { @@ -1087,7 +1087,7 @@ namespace Ink_Canvas { StrokeCollection strokes = null; string extension = Path.GetExtension(file).ToLower(); - + if (extension == ".xml") { // 从XML文件加载 diff --git a/Ink Canvas/MainWindow_cs/MW_Screenshot.cs b/Ink Canvas/MainWindow_cs/MW_Screenshot.cs index 9a548756..61632332 100644 --- a/Ink Canvas/MainWindow_cs/MW_Screenshot.cs +++ b/Ink Canvas/MainWindow_cs/MW_Screenshot.cs @@ -1,3 +1,4 @@ +using Ink_Canvas.Helpers; using System; using System.Drawing; using System.Drawing.Drawing2D; @@ -6,9 +7,8 @@ using System.IO; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; -using System.Windows.Media.Imaging; using System.Windows.Ink; -using Ink_Canvas.Helpers; +using System.Windows.Media.Imaging; namespace Ink_Canvas { diff --git a/Ink Canvas/MainWindow_cs/MW_SelectionGestures.cs b/Ink Canvas/MainWindow_cs/MW_SelectionGestures.cs index eaffd83f..046e3480 100644 --- a/Ink Canvas/MainWindow_cs/MW_SelectionGestures.cs +++ b/Ink Canvas/MainWindow_cs/MW_SelectionGestures.cs @@ -790,7 +790,7 @@ namespace Ink_Canvas var touchPoint = e.GetTouchPoint(null); centerPoint = touchPoint.Position; lastTouchPointOnGridInkCanvasCover = touchPoint.Position; - + var touchPointInCanvas = e.GetTouchPoint(inkCanvas); lastDragPointInCanvas = touchPointInCanvas.Position; } @@ -806,15 +806,15 @@ namespace Ink_Canvas dec.Remove(e.TouchDevice.Id); if (dec.Count >= 1) return; isProgramChangeStrokeSelection = false; - + lastDragPointInCanvas = new Point(0, 0); - + var touchUpPoint = e.GetTouchPoint(null).Position; if (lastTouchPointOnGridInkCanvasCover == touchUpPoint) { var touchPointInCanvas = e.GetTouchPoint(inkCanvas).Position; var selectionBounds = inkCanvas.GetSelectionBounds(); - + if (!(touchPointInCanvas.X < selectionBounds.Left) && !(touchPointInCanvas.Y < selectionBounds.Top) && !(touchPointInCanvas.X > selectionBounds.Right) && @@ -1025,8 +1025,8 @@ namespace Ink_Canvas { // 四个边选择点,向外扩展8像素 TopHandle.Margin = new Thickness(bounds.Left + bounds.Width / 2 - 4, bounds.Top - 12, 0, 0); - BottomHandle.Margin = new Thickness(bounds.Left + bounds.Width / 2 - 4, bounds.Bottom + 4 , 0, 0); - LeftHandle.Margin = new Thickness(bounds.Left - 12 , bounds.Top + bounds.Height / 2 - 4, 0, 0); + BottomHandle.Margin = new Thickness(bounds.Left + bounds.Width / 2 - 4, bounds.Bottom + 4, 0, 0); + LeftHandle.Margin = new Thickness(bounds.Left - 12, bounds.Top + bounds.Height / 2 - 4, 0, 0); RightHandle.Margin = new Thickness(bounds.Right + 4, bounds.Top + bounds.Height / 2 - 4, 0, 0); // 四个角选择点,完全位于选择框外部 diff --git a/Ink Canvas/MainWindow_cs/MW_Settings.cs b/Ink Canvas/MainWindow_cs/MW_Settings.cs index 9879daff..df90c41a 100644 --- a/Ink Canvas/MainWindow_cs/MW_Settings.cs +++ b/Ink Canvas/MainWindow_cs/MW_Settings.cs @@ -187,7 +187,7 @@ namespace Ink_Canvas // 用户同意,保存设置 Settings.Startup.HasAcceptedTelemetryPrivacy = true; Settings.Startup.TelemetryUploadLevel = TelemetryUploadLevel.Basic; - + // 更新UI,即使 isLoaded 为 false(启动时) // 使用标志避免触发事件处理程序 // 使用 Dispatcher 确保在 UI 线程上更新 @@ -245,7 +245,7 @@ namespace Ink_Canvas Settings.Startup.UpdateChannel = UpdateChannel.Release; DeviceIdentifier.UpdateUsageChannel(UpdateChannel.Release); SaveSettingsToFile(); - + Dispatcher.BeginInvoke(new Action(() => { _isChangingUpdateChannelInternally = true; @@ -288,7 +288,7 @@ namespace Ink_Canvas if (result == MessageBoxResult.Yes) { Settings.Startup.TelemetryUploadLevel = TelemetryUploadLevel.Basic; - + if (isLoaded && ComboBoxTelemetryUploadLevel != null) { ComboBoxTelemetryUploadLevel.SelectedIndex = 1; @@ -303,7 +303,7 @@ namespace Ink_Canvas Settings.Startup.UpdateChannel = UpdateChannel.Release; DeviceIdentifier.UpdateUsageChannel(UpdateChannel.Release); SaveSettingsToFile(); - + Dispatcher.BeginInvoke(new Action(() => { _isChangingUpdateChannelInternally = true; @@ -746,21 +746,21 @@ namespace Ink_Canvas if (!isLoaded) return; Settings.PowerPointSettings.PowerPointSupport = ToggleSwitchSupportPowerPoint.IsOn; - + if (!Settings.PowerPointSettings.PowerPointSupport) { if (Settings.PowerPointSettings.IsSupportWPS) { Settings.PowerPointSettings.IsSupportWPS = false; ToggleSwitchSupportWPS.IsOn = false; - + if (_pptManager != null) { _pptManager.IsSupportWPS = false; } } } - + SaveSettingsToFile(); // 使用新的PPT管理器 @@ -1266,14 +1266,14 @@ namespace Ink_Canvas { if (!isLoaded) return; Settings.Appearance.ChickenSoupSource = ComboBoxChickenSoupSource.SelectedIndex; - + if (BtnHitokotoCustomize != null) { - BtnHitokotoCustomize.Visibility = ComboBoxChickenSoupSource.SelectedIndex == 3 - ? Visibility.Visible + BtnHitokotoCustomize.Visibility = ComboBoxChickenSoupSource.SelectedIndex == 3 + ? Visibility.Visible : Visibility.Collapsed; } - + SaveSettingsToFile(); await UpdateChickenSoupTextAsync(); } @@ -1334,7 +1334,7 @@ namespace Ink_Canvas // 全选复选框逻辑 bool isUpdatingSelectAll = false; selectAllCheckBox.IsChecked = Settings.Appearance.HitokotoCategories.Count == categories.Count; - + selectAllCheckBox.Checked += (s, args) => { if (isUpdatingSelectAll) return; @@ -1423,7 +1423,7 @@ namespace Ink_Canvas } SaveSettingsToFile(); - + // 如果当前正在使用API,更新名言 if (Settings.Appearance.ChickenSoupSource == 3 && Settings.Appearance.EnableChickenSoupInWhiteboardMode) { @@ -5125,8 +5125,8 @@ namespace Ink_Canvas { var oldChannel = Settings.Startup.UpdateChannel; string channel = radioButton.Tag.ToString(); - UpdateChannel newChannel = channel == "Beta" ? UpdateChannel.Beta - : channel == "Preview" ? UpdateChannel.Preview + UpdateChannel newChannel = channel == "Beta" ? UpdateChannel.Beta + : channel == "Preview" ? UpdateChannel.Preview : UpdateChannel.Release; // 如果通道没有变化,不需要执行更新检查 diff --git a/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs b/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs index 27f71bd6..23000346 100644 --- a/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs +++ b/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs @@ -418,15 +418,15 @@ namespace Ink_Canvas ComboBoxTheme.SelectedIndex = Settings.Appearance.Theme; ComboBoxChickenSoupSource.SelectedIndex = Settings.Appearance.ChickenSoupSource; - + // 初始化自定义按钮的可见性(仅在选择API时显示) if (BtnHitokotoCustomize != null) { - BtnHitokotoCustomize.Visibility = Settings.Appearance.ChickenSoupSource == 3 - ? Visibility.Visible + BtnHitokotoCustomize.Visibility = Settings.Appearance.ChickenSoupSource == 3 + ? Visibility.Visible : Visibility.Collapsed; } - + // 初始化HitokotoCategories,如果为空则默认全选 if (Settings.Appearance.HitokotoCategories == null || Settings.Appearance.HitokotoCategories.Count == 0) { @@ -1307,7 +1307,7 @@ namespace Ink_Canvas { if (string.IsNullOrWhiteSpace(Settings.Canvas.BrushAutoRestoreColor)) { - Settings.Canvas.BrushAutoRestoreColor = "#FFFF0000"; + Settings.Canvas.BrushAutoRestoreColor = "#FFFF0000"; } bool found = false; @@ -1328,13 +1328,13 @@ namespace Ink_Canvas break; } } - + if (!found && ComboBoxBrushAutoRestoreColor.Items.Count > 0) { ComboBoxBrushAutoRestoreColor.SelectionChanged -= ComboBoxBrushAutoRestoreColor_SelectionChanged; try { - ComboBoxBrushAutoRestoreColor.SelectedIndex = 0; + ComboBoxBrushAutoRestoreColor.SelectedIndex = 0; Settings.Canvas.BrushAutoRestoreColor = "#FFFF0000"; } finally @@ -1347,8 +1347,8 @@ namespace Ink_Canvas // 同步粗细滑块 if (BrushAutoRestoreWidthSlider != null) { - BrushAutoRestoreWidthSlider.Value = Settings.Canvas.BrushAutoRestoreWidth > 0 - ? Settings.Canvas.BrushAutoRestoreWidth + BrushAutoRestoreWidthSlider.Value = Settings.Canvas.BrushAutoRestoreWidth > 0 + ? Settings.Canvas.BrushAutoRestoreWidth : 5; } diff --git a/Ink Canvas/MainWindow_cs/MW_ShapeDrawing.cs b/Ink Canvas/MainWindow_cs/MW_ShapeDrawing.cs index dd0617b6..b18958ec 100644 --- a/Ink Canvas/MainWindow_cs/MW_ShapeDrawing.cs +++ b/Ink Canvas/MainWindow_cs/MW_ShapeDrawing.cs @@ -2082,12 +2082,12 @@ namespace Ink_Canvas /// 用于标识是否是长方体绘制的第一次触摸,第一次触摸绘制正面矩形,第二次触摸绘制深度 /// private bool isFirstTouchCuboid = true; - + /// /// 长方体正面矩形的起始点 /// private Point CuboidFrontRectIniP; - + /// /// 长方体正面矩形的结束点 /// @@ -2100,7 +2100,7 @@ namespace Ink_Canvas /// 用于存储当前正在绘制的临时笔画,在绘制过程中实时更新 /// private Stroke lastTempStroke; - + /// /// 上一次的临时笔画集合 /// @@ -2122,7 +2122,7 @@ namespace Ink_Canvas /// 上一次更新时间 /// private DateTime lastUpdateTime = DateTime.MinValue; - + /// /// 更新节流时间(毫秒) /// @@ -2493,7 +2493,7 @@ namespace Ink_Canvas /// 用于标识鼠标是否处于按下状态,在绘制过程中使用 /// private bool isMouseDown; - + /// /// 触摸按下状态标志 /// @@ -2537,7 +2537,7 @@ namespace Ink_Canvas private void inkCanvas_MouseMove(object sender, MouseEventArgs e) { if (isMouseDown) MouseTouchMove(e.GetPosition(inkCanvas)); - + if (Settings.Canvas.IsShowCursor) { SetCursorBasedOnEditingMode(inkCanvas); diff --git a/Ink Canvas/MainWindow_cs/MW_SimulatePressure&InkToShape.cs b/Ink Canvas/MainWindow_cs/MW_SimulatePressure&InkToShape.cs index fece8702..50138c38 100644 --- a/Ink Canvas/MainWindow_cs/MW_SimulatePressure&InkToShape.cs +++ b/Ink Canvas/MainWindow_cs/MW_SimulatePressure&InkToShape.cs @@ -1408,7 +1408,7 @@ namespace Ink_Canvas double dx = end.X - start.X; double dy = end.Y - start.Y; double lineLength = Math.Sqrt(dx * dx + dy * dy); - + if (lineLength > 1e-10) { directionX = dx / lineLength; @@ -1693,13 +1693,13 @@ namespace Ink_Canvas else { Point midPoint = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2); - + var startToMid = GeneratePointsBetween(start, midPoint, 0.4f, 0.8f, 8.0); foreach (var pt in startToMid) { points.Add(pt); } - + var midToEnd = GeneratePointsBetween(midPoint, end, 0.8f, 0.4f, 8.0); for (int i = 1; i < midToEnd.Count; i++) { @@ -2030,7 +2030,7 @@ namespace Ink_Canvas { double deltaY = Math.Abs(p1.Y - p2.Y); double deltaX = Math.Abs(p1.X - p2.X); - + if (deltaY < 1e-10 || deltaX / deltaY > 8) { //水平 @@ -2068,7 +2068,7 @@ namespace Ink_Canvas public StylusPointCollection GenerateFakePressureTriangle(StylusPointCollection points) { var newPoint = new StylusPointCollection(); - + if (Settings.InkToShape.IsInkToShapeNoFakePressureTriangle || penType == 1) { if (points.Count >= 3) @@ -2114,9 +2114,9 @@ namespace Ink_Canvas { Point start = points[i].ToPoint(); Point end = points[(i + 1) % 3].ToPoint(); - + Point midPoint = GetCenterPoint(start, end); - + var startToMid = GeneratePointsBetween(start, midPoint, 0.4f, 0.8f, 8.0); if (i == 0) { @@ -2132,7 +2132,7 @@ namespace Ink_Canvas newPoint.Add(startToMid[j]); } } - + var midToEnd = GeneratePointsBetween(midPoint, end, 0.8f, 0.4f, 8.0); for (int j = 1; j < midToEnd.Count; j++) { @@ -2161,18 +2161,18 @@ namespace Ink_Canvas { var result = new StylusPointCollection(); double distance = GetDistance(start, end); - + if (distance < minPointInterval) { result.Add(new StylusPoint(start.X, start.Y, startPressure)); result.Add(new StylusPoint(end.X, end.Y, endPressure)); return result; } - + int pointCount = Math.Max(2, (int)(distance / minPointInterval) + 1); - + result.Add(new StylusPoint(start.X, start.Y, startPressure)); - + for (int i = 1; i < pointCount - 1; i++) { double ratio = (double)i / (pointCount - 1); @@ -2181,16 +2181,16 @@ namespace Ink_Canvas double y = start.Y + (end.Y - start.Y) * ratio; result.Add(new StylusPoint(x, y, (float)pressure)); } - + result.Add(new StylusPoint(end.X, end.Y, endPressure)); - + return result; } public StylusPointCollection GenerateFakePressureRectangle(StylusPointCollection points) { var newPoint = new StylusPointCollection(); - + if (Settings.InkToShape.IsInkToShapeNoFakePressureRectangle || penType == 1) { if (points.Count >= 4) @@ -2229,9 +2229,9 @@ namespace Ink_Canvas { Point start = points[i].ToPoint(); Point end = points[(i + 1) % 4].ToPoint(); - + Point midPoint = GetCenterPoint(start, end); - + var startToMid = GeneratePointsBetween(start, midPoint, 0.4f, 0.8f, 8.0); if (i == 0) { @@ -2247,7 +2247,7 @@ namespace Ink_Canvas newPoint.Add(startToMid[j]); } } - + var midToEnd = GeneratePointsBetween(midPoint, end, 0.8f, 0.4f, 8.0); for (int j = 1; j < midToEnd.Count; j++) { @@ -2259,7 +2259,7 @@ namespace Ink_Canvas { return points; } - + return newPoint; } diff --git a/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs b/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs index 73d6fabc..85a3624f 100644 --- a/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs +++ b/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs @@ -35,27 +35,27 @@ namespace Ink_Canvas /// 当前提交类型 /// private CommitReason _currentCommitType = CommitReason.UserInput; - + /// /// 是否为点橡皮擦模式 /// private bool IsEraseByPoint => inkCanvas.EditingMode == InkCanvasEditingMode.EraseByPoint; - + /// /// 替换的笔画集合 /// private StrokeCollection ReplacedStroke; - + /// /// 添加的笔画集合 /// private StrokeCollection AddedStroke; - + /// /// 长方体笔画集合 /// private StrokeCollection CuboidStrokeCollection; - + /// /// 笔画操作历史记录 /// diff --git a/Ink Canvas/MainWindow_cs/MW_Timer.cs b/Ink Canvas/MainWindow_cs/MW_Timer.cs index 3489b377..c51f68e5 100644 --- a/Ink Canvas/MainWindow_cs/MW_Timer.cs +++ b/Ink Canvas/MainWindow_cs/MW_Timer.cs @@ -743,7 +743,7 @@ namespace Ink_Canvas { return true; } - else if (Settings.Automation.IsAutoFoldInSeewoPincoTeacher && + else if (Settings.Automation.IsAutoFoldInSeewoPincoTeacher && (windowProcessName == "BoardService" || windowProcessName == "seewoPincoTeacher")) { return true; @@ -760,7 +760,7 @@ namespace Ink_Canvas { return true; } - else if (Settings.Automation.IsAutoFoldInMSWhiteboard && + else if (Settings.Automation.IsAutoFoldInMSWhiteboard && (windowProcessName == "MicrosoftWhiteboard" || windowProcessName == "msedgewebview2")) { return true; @@ -899,7 +899,7 @@ namespace Ink_Canvas return true; } // 检查SeewoPinco - else if (Settings.Automation.IsAutoFoldInSeewoPincoTeacher && + else if (Settings.Automation.IsAutoFoldInSeewoPincoTeacher && (windowProcessName == "BoardService" || windowProcessName == "seewoPincoTeacher")) { return true; @@ -926,7 +926,7 @@ namespace Ink_Canvas return true; } // 检查MSWhiteboard - else if (Settings.Automation.IsAutoFoldInMSWhiteboard && + else if (Settings.Automation.IsAutoFoldInMSWhiteboard && (windowProcessName == "MicrosoftWhiteboard" || windowProcessName == "msedgewebview2")) { return true; @@ -1027,19 +1027,20 @@ namespace Ink_Canvas var windowTitle = ForegroundWindowInfo.WindowTitle(); Thickness currentMargin = new Thickness(); - Dispatcher.Invoke(() => { + Dispatcher.Invoke(() => + { currentMargin = ViewboxFloatingBar.Margin; }); - + if (hasFullScreen) { - if (!isFloatingBarFolded) + if (!isFloatingBarFolded) { FoldFloatingBar_MouseUp(null, null); } else if (currentMargin.Left > -50 && !isFloatingBarChangingHideMode) { - FoldFloatingBar_MouseUp(null, null); + FoldFloatingBar_MouseUp(null, null); } return; } @@ -1052,20 +1053,20 @@ namespace Ink_Canvas { var versionInfo = FileVersionInfo.GetVersionInfo(ForegroundWindowInfo.ProcessPath()); string version = versionInfo.FileVersion; - + if (version.StartsWith("5.") && Settings.Automation.IsAutoFoldInEasiNote) { bool isAnnotationWindow = windowTitle.Length == 0 && ForegroundWindowInfo.WindowRect().Height < 500; if (Settings.Automation.IsAutoFoldInEasiNoteIgnoreDesktopAnno && isAnnotationWindow) { - if (!isFloatingBarFolded) + if (!isFloatingBarFolded) { FoldFloatingBar_MouseUp(null, null); } } else if (!isAnnotationWindow) { - if (!unfoldFloatingBarByUser && !isFloatingBarFolded) + if (!unfoldFloatingBarByUser && !isFloatingBarFolded) { FoldFloatingBar_MouseUp(null, null); } @@ -1457,7 +1458,7 @@ namespace Ink_Canvas try { // 检查是否仍然在橡皮擦模式 - if (inkCanvas.EditingMode != InkCanvasEditingMode.EraseByPoint && + if (inkCanvas.EditingMode != InkCanvasEditingMode.EraseByPoint && inkCanvas.EditingMode != InkCanvasEditingMode.EraseByStroke) { StopEraserAutoSwitchBackTimer(); diff --git a/Ink Canvas/MainWindow_cs/MW_TouchEvents.cs b/Ink Canvas/MainWindow_cs/MW_TouchEvents.cs index 9705be21..48f46d7e 100644 --- a/Ink Canvas/MainWindow_cs/MW_TouchEvents.cs +++ b/Ink Canvas/MainWindow_cs/MW_TouchEvents.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; -using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; diff --git a/Ink Canvas/MainWindow_cs/MW_UriHandler.cs b/Ink Canvas/MainWindow_cs/MW_UriHandler.cs index f9cfa220..cbf0059a 100644 --- a/Ink Canvas/MainWindow_cs/MW_UriHandler.cs +++ b/Ink Canvas/MainWindow_cs/MW_UriHandler.cs @@ -1,9 +1,7 @@ using Ink_Canvas.Helpers; using Newtonsoft.Json; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Windows; namespace Ink_Canvas @@ -121,12 +119,12 @@ namespace Ink_Canvas CursorIcon_Click(null, null); break; case "eraser": - PenIcon_Click(null, null); + PenIcon_Click(null, null); EraserIcon_Click(null, null); break; case "eraserbystrokes": case "eraserstroke": - PenIcon_Click(null, null); + PenIcon_Click(null, null); EraserIconByStrokes_Click(EraserByStrokes_Icon, null); break; default: diff --git a/Ink Canvas/MainWindow_cs/MW_VideoPresenter.cs b/Ink Canvas/MainWindow_cs/MW_VideoPresenter.cs index 66b75ea9..b8be0c01 100644 --- a/Ink Canvas/MainWindow_cs/MW_VideoPresenter.cs +++ b/Ink Canvas/MainWindow_cs/MW_VideoPresenter.cs @@ -11,7 +11,6 @@ using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; -using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; @@ -609,12 +608,12 @@ namespace Ink_Canvas { var ci = new CapturedImage(bmpImage); _capturedPhotos.Insert(0, ci); - + while (_capturedPhotos.Count > MaxCapturedPhotos) { _capturedPhotos.RemoveAt(_capturedPhotos.Count - 1); } - + UpdateCapturedPhotosDisplay(); })); } diff --git a/Ink Canvas/MarkupExtensions/I18nExtension.cs b/Ink Canvas/MarkupExtensions/I18nExtension.cs index 7353ecb5..bdc8be21 100644 --- a/Ink Canvas/MarkupExtensions/I18nExtension.cs +++ b/Ink Canvas/MarkupExtensions/I18nExtension.cs @@ -1,6 +1,6 @@ +using Ink_Canvas.Properties; using System; using System.Windows.Markup; -using Ink_Canvas.Properties; namespace Ink_Canvas.MarkupExtensions { diff --git a/Ink Canvas/Models/CapturedImage.cs b/Ink Canvas/Models/CapturedImage.cs index a871b930..bbd7a149 100644 --- a/Ink Canvas/Models/CapturedImage.cs +++ b/Ink Canvas/Models/CapturedImage.cs @@ -144,7 +144,7 @@ namespace Ink_Canvas.Models double targetWidth = 290.0; double targetHeight = 180.0; double scale = Math.Min(targetWidth / original.PixelWidth, targetHeight / original.PixelHeight); - + if (double.IsInfinity(scale) || double.IsNaN(scale) || scale <= 0) { throw new InvalidOperationException( diff --git a/Ink Canvas/Resources/Settings.cs b/Ink Canvas/Resources/Settings.cs index 23a93ca9..d2a9ebd8 100644 --- a/Ink Canvas/Resources/Settings.cs +++ b/Ink Canvas/Resources/Settings.cs @@ -136,7 +136,7 @@ namespace Ink_Canvas [JsonProperty("brushAutoRestoreColor")] public string BrushAutoRestoreColor { get; set; } = "#FFFF0000"; [JsonProperty("brushAutoRestoreWidth")] - public double BrushAutoRestoreWidth { get; set; } =5; + public double BrushAutoRestoreWidth { get; set; } = 5; [JsonProperty("brushAutoRestoreAlpha")] public int BrushAutoRestoreAlpha { get; set; } = 255; [JsonProperty("enableEraserAutoSwitchBack")] @@ -403,7 +403,7 @@ namespace Ink_Canvas [JsonProperty("enablePPTTimeCapsule")] public bool EnablePPTTimeCapsule { get; set; } = true; [JsonProperty("pptTimeCapsulePosition")] - public int PPTTimeCapsulePosition { get; set; } = 1; + public int PPTTimeCapsulePosition { get; set; } = 1; [JsonProperty("useRotPptLink")] public bool UseRotPptLink { get; set; } = false; [JsonProperty("showPPTSidebarByDefault")] @@ -448,7 +448,7 @@ namespace Ink_Canvas [JsonProperty("isAutoFoldInEasiNote3")] public bool IsAutoFoldInEasiNote3 { get; set; } - + [JsonProperty("isAutoFoldInEasiNote3C")] public bool IsAutoFoldInEasiNote3C { get; set; } diff --git a/Ink Canvas/Windows/CloudStorageManagementWindow.xaml.cs b/Ink Canvas/Windows/CloudStorageManagementWindow.xaml.cs index b55aec5e..3bc966fe 100644 --- a/Ink Canvas/Windows/CloudStorageManagementWindow.xaml.cs +++ b/Ink Canvas/Windows/CloudStorageManagementWindow.xaml.cs @@ -7,7 +7,6 @@ using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using MessageBox = iNKORE.UI.WPF.Modern.Controls.MessageBox; -using ui = iNKORE.UI.WPF.Modern.Controls; namespace Ink_Canvas.Windows { @@ -327,7 +326,7 @@ namespace Ink_Canvas.Windows if (MainWindow.Settings?.Dlass != null) { MainWindow.Settings.Dlass.IsAutoUploadNotes = ToggleSwitchAutoUploadNotes.IsOn; - + // 同步更新到EnabledProviders列表 if (MainWindow.Settings.Upload != null) { @@ -335,7 +334,7 @@ namespace Ink_Canvas.Windows { MainWindow.Settings.Upload.EnabledProviders = new List(); } - + bool isAutoUploadEnabled = ToggleSwitchAutoUploadNotes.IsOn; bool isDlassInEnabledProviders = MainWindow.Settings.Upload.EnabledProviders.Contains("Dlass"); bool isAlreadyConsistent = (isAutoUploadEnabled == isDlassInEnabledProviders); @@ -346,7 +345,7 @@ namespace Ink_Canvas.Windows MainWindow.SaveSettingsToFile(); return; } - + if (isAutoUploadEnabled) { if (!MainWindow.Settings.Upload.EnabledProviders.Contains("Dlass")) @@ -358,11 +357,11 @@ namespace Ink_Canvas.Windows { MainWindow.Settings.Upload.EnabledProviders.Remove("Dlass"); } - + // 重新加载通用设置,更新UI LoadUniversalUploadSettings(); } - + MainWindow.SaveSettingsToFile(); } } @@ -494,7 +493,7 @@ namespace Ink_Canvas.Windows { MainWindow.Settings.Upload.EnabledProviders.Remove(provider.Name); } - + // 同步更新Dlass的IsAutoUploadNotes设置(如果是Dlass提供者) if (provider.Name == "Dlass" && MainWindow.Settings.Dlass != null) { diff --git a/Ink Canvas/Windows/NewStyleRollCallWindow.xaml.cs b/Ink Canvas/Windows/NewStyleRollCallWindow.xaml.cs index c4eabbb8..54880fb3 100644 --- a/Ink Canvas/Windows/NewStyleRollCallWindow.xaml.cs +++ b/Ink Canvas/Windows/NewStyleRollCallWindow.xaml.cs @@ -180,8 +180,8 @@ namespace Ink_Canvas private const double PROBABILITY_RECOVERY_RATE = 0.2; private const double FREQUENCY_BOOST_FACTOR = 2.0; - private const int MaxGapThreshold = 3; - private const int MinCandidatePoolSize = 2; + private const int MaxGapThreshold = 3; + private const int MinCandidatePoolSize = 2; // 单次抽相关 private bool isSingleDrawMode = false; diff --git a/Ink Canvas/Windows/OobeWindow.xaml.cs b/Ink Canvas/Windows/OobeWindow.xaml.cs index e4036bdc..4c8990e1 100644 --- a/Ink Canvas/Windows/OobeWindow.xaml.cs +++ b/Ink Canvas/Windows/OobeWindow.xaml.cs @@ -10,7 +10,7 @@ namespace Ink_Canvas.Windows { private readonly Settings _settings; private int _currentStep = 0; - private const int MaxStepIndex = 11; + private const int MaxStepIndex = 11; /// /// 初始化 OobeWindow,并使用指定的 Settings 填充初始状态与界面。 diff --git a/Ink Canvas/Windows/PPTQuickPanel.xaml.cs b/Ink Canvas/Windows/PPTQuickPanel.xaml.cs index ffda3e3d..c3a4b9bf 100644 --- a/Ink Canvas/Windows/PPTQuickPanel.xaml.cs +++ b/Ink Canvas/Windows/PPTQuickPanel.xaml.cs @@ -1,4 +1,6 @@ using Ink_Canvas.Helpers; +using Microsoft.Win32; +using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.Specialized; @@ -12,8 +14,6 @@ using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Threading; -using Microsoft.Win32; -using Newtonsoft.Json; using SystemEvents = Microsoft.Win32.SystemEvents; namespace Ink_Canvas.Windows @@ -100,9 +100,9 @@ namespace Ink_Canvas.Windows private Point _dragStartPoint; private double _collapsedOffset = 200; // 折叠时的偏移量(隐藏内容区域) private MainWindow _mainWindow; - + private Dictionary _pptImages = new Dictionary(); - + private Dictionary> _pptImagePaths = new Dictionary>(); public PPTQuickPanel() @@ -110,10 +110,10 @@ namespace Ink_Canvas.Windows InitializeComponent(); InitializeAudio(); ApplyTheme(); - + // 监听主题变化 SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged; - + Loaded += PPTQuickPanel_Loaded; Unloaded += PPTQuickPanel_Unloaded; IsVisibleChanged += PPTQuickPanel_IsVisibleChanged; @@ -132,10 +132,10 @@ namespace Ink_Canvas.Windows // 初始状态为折叠 PanelTransform.X = _collapsedOffset; UpdateArrowRotation(); - + // 获取MainWindow引用 _mainWindow = Application.Current.MainWindow as MainWindow; - + SubscribeToPPTEvents(); SubscribeToInkCanvasChildrenChanges(); Dispatcher.BeginInvoke(new Action(() => @@ -143,15 +143,15 @@ namespace Ink_Canvas.Windows UpdateVolumeDisplay(); }), DispatcherPriority.Loaded); } - + private void SubscribeToInkCanvasChildrenChanges() { try { if (_mainWindow == null) return; - + System.Windows.Controls.InkCanvas inkCanvas = null; - var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", + var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (inkCanvasField != null) { @@ -159,11 +159,11 @@ namespace Ink_Canvas.Windows } if (inkCanvas == null) { - var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", + var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); inkCanvas = inkCanvasProperty?.GetValue(_mainWindow) as System.Windows.Controls.InkCanvas; } - + if (inkCanvas != null && inkCanvas.Children is INotifyCollectionChanged notifyCollection) { notifyCollection.CollectionChanged += InkCanvasChildren_CollectionChanged; @@ -174,7 +174,7 @@ namespace Ink_Canvas.Windows LogHelper.WriteLogToFile($"订阅inkCanvas.Children变化事件失败: {ex.Message}", LogHelper.LogType.Error); } } - + private void InkCanvasChildren_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { try @@ -195,25 +195,25 @@ namespace Ink_Canvas.Windows LogHelper.WriteLogToFile($"处理inkCanvas.Children变化失败: {ex.Message}", LogHelper.LogType.Error); } } - + private void RemoveImageFromPPT(System.Windows.Controls.Image image) { try { if (image == null) return; - + if (_pptImages.ContainsKey(image)) { int slideNumber = _pptImages[image]; _pptImages.Remove(image); - + if (_pptImagePaths.ContainsKey(slideNumber)) { string imagePath = image.Tag as string; if (!string.IsNullOrEmpty(imagePath) && _pptImagePaths[slideNumber].Contains(imagePath)) { _pptImagePaths[slideNumber].Remove(imagePath); - + if (_pptImagePaths[slideNumber].Count == 0) { _pptImagePaths.Remove(slideNumber); @@ -223,7 +223,7 @@ namespace Ink_Canvas.Windows { SavePPTImagePaths(slideNumber); } - + LogHelper.WriteLogToFile($"已从PPT页面{slideNumber}移除图片: {imagePath}"); } } @@ -234,17 +234,17 @@ namespace Ink_Canvas.Windows LogHelper.WriteLogToFile($"从PPT关联数据中移除图片失败: {ex.Message}", LogHelper.LogType.Error); } } - + private void DeletePPTImagePathsFile(int slideIndex) { try { if (slideIndex <= 0) return; - + var folderPath = GetPresentationFolderPath(); - if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath)) + if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath)) return; - + var jsonFilePath = Path.Combine(folderPath, slideIndex.ToString("0000") + ".images.json"); if (File.Exists(jsonFilePath)) { @@ -257,18 +257,18 @@ namespace Ink_Canvas.Windows LogHelper.WriteLogToFile($"删除PPT图片路径JSON文件失败: {ex.Message}", LogHelper.LogType.Error); } } - + private void SubscribeToPPTEvents() { try { if (_mainWindow == null) return; - + // 获取PPTManager - var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", + var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); var pptManager = pptManagerProperty?.GetValue(_mainWindow); - + if (pptManager != null) { // 订阅PPT演示文稿打开事件 @@ -278,7 +278,7 @@ namespace Ink_Canvas.Windows var openHandler = new Action(OnPPTPresentationOpen); presentationOpenEvent.AddEventHandler(pptManager, openHandler); } - + // 订阅PPT开始事件 var slideShowBeginEvent = pptManager.GetType().GetEvent("SlideShowBegin"); if (slideShowBeginEvent != null) @@ -286,7 +286,7 @@ namespace Ink_Canvas.Windows var beginHandler = new Action(OnPPTSlideShowBegin); slideShowBeginEvent.AddEventHandler(pptManager, beginHandler); } - + // 订阅PPT翻页事件 var slideShowNextSlideEvent = pptManager.GetType().GetEvent("SlideShowNextSlide"); if (slideShowNextSlideEvent != null) @@ -294,7 +294,7 @@ namespace Ink_Canvas.Windows var handler = new Action(OnPPTSlideChanged); slideShowNextSlideEvent.AddEventHandler(pptManager, handler); } - + // 订阅PPT结束事件 var slideShowEndEvent = pptManager.GetType().GetEvent("SlideShowEnd"); if (slideShowEndEvent != null) @@ -309,7 +309,7 @@ namespace Ink_Canvas.Windows LogHelper.WriteLogToFile($"订阅PPT事件失败: {ex.Message}", LogHelper.LogType.Error); } } - + private void OnPPTPresentationOpen(object presentation) { Application.Current.Dispatcher.BeginInvoke(new Action(() => @@ -325,7 +325,7 @@ namespace Ink_Canvas.Windows } }), DispatcherPriority.Normal); } - + private void OnPPTSlideShowBegin(object window) { Application.Current.Dispatcher.BeginInvoke(new Action(async () => @@ -334,14 +334,14 @@ namespace Ink_Canvas.Windows { // PPT开始时,加载所有图片路径并加载当前页面的图片 LoadAllPPTImagePaths(); - + if (_mainWindow == null) return; - + // 获取当前PPT页面编号 - var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", + var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); var pptManager = pptManagerProperty?.GetValue(_mainWindow); - + if (pptManager != null) { var getCurrentSlideNumberMethod = pptManager.GetType().GetMethod("GetCurrentSlideNumber"); @@ -354,7 +354,7 @@ namespace Ink_Canvas.Windows currentSlide = (int)result; } } - + // 加载当前页面的图片 if (currentSlide > 0) { @@ -368,7 +368,7 @@ namespace Ink_Canvas.Windows } }), DispatcherPriority.Normal); } - + private void OnPPTSlideChanged(object window) { Application.Current.Dispatcher.BeginInvoke(new Action(async () => @@ -376,12 +376,12 @@ namespace Ink_Canvas.Windows try { if (_mainWindow == null) return; - + // 获取当前PPT页面编号 - var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", + var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); var pptManager = pptManagerProperty?.GetValue(_mainWindow); - + if (pptManager != null) { var getCurrentSlideNumberMethod = pptManager.GetType().GetMethod("GetCurrentSlideNumber"); @@ -394,10 +394,10 @@ namespace Ink_Canvas.Windows currentSlide = (int)result; } } - + // 更新图片可见性 UpdatePPTImagesVisibility(currentSlide); - + // 加载当前页面的图片(如果还没有加载) if (currentSlide > 0 && (!_pptImagePaths.ContainsKey(currentSlide) || _pptImagePaths[currentSlide].Count == 0)) { @@ -406,7 +406,7 @@ namespace Ink_Canvas.Windows if (imagePaths != null && imagePaths.Count > 0) { _pptImagePaths[currentSlide] = imagePaths; - + // 加载图片 await LoadPPTImages(currentSlide); } @@ -419,7 +419,7 @@ namespace Ink_Canvas.Windows } }), DispatcherPriority.Normal); } - + private void OnPPTSlideShowEnd(object presentation) { Application.Current.Dispatcher.BeginInvoke(new Action(() => @@ -435,7 +435,7 @@ namespace Ink_Canvas.Windows } }), DispatcherPriority.Normal); } - + private void UpdatePPTImagesVisibility(int currentSlide) { try @@ -444,7 +444,7 @@ namespace Ink_Canvas.Windows { var image = kvp.Key; var slideNumber = kvp.Value; - + // 如果图片在当前页面,显示;否则隐藏 image.Visibility = (slideNumber == currentSlide) ? Visibility.Visible : Visibility.Collapsed; } @@ -454,7 +454,7 @@ namespace Ink_Canvas.Windows LogHelper.WriteLogToFile($"更新PPT图片可见性失败: {ex.Message}", LogHelper.LogType.Error); } } - + private void HideAllPPTImages() { try @@ -475,15 +475,15 @@ namespace Ink_Canvas.Windows SystemEvents.UserPreferenceChanged -= SystemEvents_UserPreferenceChanged; UnsubscribeFromInkCanvasChildrenChanges(); } - + private void UnsubscribeFromInkCanvasChildrenChanges() { try { if (_mainWindow == null) return; - + System.Windows.Controls.InkCanvas inkCanvas = null; - var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", + var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (inkCanvasField != null) { @@ -491,11 +491,11 @@ namespace Ink_Canvas.Windows } if (inkCanvas == null) { - var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", + var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); inkCanvas = inkCanvasProperty?.GetValue(_mainWindow) as System.Windows.Controls.InkCanvas; } - + if (inkCanvas != null && inkCanvas.Children is INotifyCollectionChanged notifyCollection) { notifyCollection.CollectionChanged -= InkCanvasChildren_CollectionChanged; @@ -524,7 +524,7 @@ namespace Ink_Canvas.Windows var deviceEnumerator = MMDeviceEnumeratorFactory.CreateInstance(); IMMDevice device; deviceEnumerator.GetDefaultAudioEndpoint(eRender, eConsole, out device); - + Guid IID_IAudioEndpointVolume = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A"); object interfacePointer; device.Activate(ref IID_IAudioEndpointVolume, 0, IntPtr.Zero, out interfacePointer); @@ -596,20 +596,20 @@ namespace Ink_Canvas.Windows private void UpdateVolumeDisplay() { if (_audioEndpointVolume == null) return; - + try { float volume = GetVolume(); bool isMuted = GetMute(); - + // 更新滑块值(不触发事件) VolumeSlider.ValueChanged -= VolumeSlider_ValueChanged; VolumeSlider.Value = volume * 100; VolumeSlider.ValueChanged += VolumeSlider_ValueChanged; - + // 更新文本显示 VolumeValueText.Text = $"{(int)(volume * 100)}%"; - + // 更新图标 UpdateVolumeIcon(isMuted, volume); } @@ -626,10 +626,10 @@ namespace Ink_Canvas.Windows VolumeIconPath.StrokeThickness = 0; VolumeIconPath2.Stroke = null; VolumeIconPath2.StrokeThickness = 0; - + // 默认隐藏第二个Path VolumeIconPath2.Visibility = Visibility.Collapsed; - + // 静音或音量为0%时显示静音图标 if (isMuted || volume <= 0f) { @@ -638,7 +638,7 @@ namespace Ink_Canvas.Windows var speakerGeometry = Geometry.Parse("M 7,1.00772 C 6.70313,1.00381 6.42188,1.13272 6.23048,1.35928 L 3,4.99991 H 2 C 0.906251,4.99991 0,5.84366 0,6.99991 V 8.99991 C 0,10.0898 0.910157,10.9999 2,10.9999 H 3 L 6.23048,14.6405 C 6.44141,14.8944 6.72266,15.0038 7,14.9999 V 1.00772 Z"); // X部分 var xGeometry = Geometry.Parse("M 10,5.00012 C 9.73441,5.00012 9.4805,5.10559 9.293,5.29309 C 8.90237,5.68372 8.90237,6.31653 9.293,6.70715 L 10.586,8.00013 L 9.293,9.2931 C 8.90237,9.68372 8.90237,10.3165 9.293,10.7072 C 9.68362,11.0978 10.3164,11.0978 10.7071,10.7072 L 12,9.41419 L 13.293,10.7072 C 13.6836,11.0978 14.3164,11.0978 14.7071,10.7072 C 15.0977,10.3165 15.0977,9.68372 14.7071,9.2931 L 13.4141,8.00013 L 14.7071,6.70715 C 15.0977,6.31653 15.0977,5.68372 14.7071,5.29309 C 14.5196,5.10559 14.2657,5.00012 14,5.00012 C 13.7344,5.00012 13.4805,5.10559 13.293,5.29309 L 12,6.58606 L 10.7071,5.29309 C 10.5196,5.10559 10.2657,5.00012 10,5.00012 Z"); - + var group = new GeometryGroup(); group.Children.Add(speakerGeometry); group.Children.Add(xGeometry); @@ -654,7 +654,7 @@ namespace Ink_Canvas.Windows var wave1Geometry = Geometry.Parse("M 13.461,0.961025 C 13.2695,0.957119 13.0742,1.01571 12.9024,1.12899 C 12.4453,1.44149 12.3242,2.06259 12.6328,2.51962 C 14.457,5.22666 14.457,8.75791 12.6328,11.4649 C 12.3242,11.922 12.4453,12.5431 12.9024,12.8556 C 13.3594,13.1642 13.9805,13.0431 14.293,12.586 C 15.4297,10.8946 16,8.94541 16,6.99228 C 16,5.03915 15.4297,3.08993 14.293,1.39853 C 14.0977,1.11337 13.7813,0.961025 13.461,0.961025 Z"); // 第二条声波线 var wave2Geometry = Geometry.Parse("M 10.0391,2.98056 C 9.81642,2.97275 9.58595,3.03915 9.39454,3.18368 C 9.13282,3.3829 9.00001,3.68368 9.00001,3.98837 V 4.04697 C 9.01173,4.23837 9.07423,4.42197 9.19923,4.58212 C 10.2734,6.01181 10.2734,7.97275 9.19923,9.39853 C 9.07423,9.5626 9.01173,9.74619 9.00001,9.93369 V 9.99619 C 9.00001,10.3009 9.13282,10.6017 9.39454,10.8009 C 9.83595,11.1329 10.4609,11.0431 10.793,10.6017 C 11.5977,9.53525 12,8.26572 12,6.99228 C 12,5.71884 11.5977,4.44931 10.793,3.379 C 10.6094,3.1329 10.3281,2.99618 10.0391,2.98056 Z"); - + var group = new GeometryGroup(); group.Children.Add(speakerGeometry); group.Children.Add(wave1Geometry); @@ -669,13 +669,13 @@ namespace Ink_Canvas.Windows var speakerGeometry = Geometry.Parse("M 7,1.00759 C 6.70313,1.00369 6.42188,1.13259 6.23048,1.35916 L 3,4.99979 H 2 C 0.906251,4.99979 0,5.84354 0,6.99979 V 8.99979 C 0,10.0896 0.910157,10.9998 2,10.9998 H 3 L 6.23048,14.6404 C 6.44141,14.8943 6.72266,15.0037 7,14.9998 V 1.00759 Z"); // 声波线(实线,不透明度100%) var wave1Geometry = Geometry.Parse("M 10.0391,3.98807 C 9.81642,3.98025 9.58595,4.04666 9.39454,4.19119 C 9.13282,4.39041 9.00001,4.69119 9.00001,4.99588 V 5.06229 C 9.01173,5.24979 9.07813,5.43338 9.19923,5.58963 C 10.2734,7.01932 10.2734,8.98026 9.19923,10.406 C 9.07813,10.5662 9.01173,10.7498 9.00001,10.9373 V 11.0037 C 9.00001,11.3084 9.13282,11.6092 9.39454,11.8084 C 9.83595,12.1404 10.4609,12.0506 10.793,11.6092 C 11.5977,10.5428 12,9.27323 12,7.99979 C 12,6.72635 11.5977,5.45682 10.793,4.3865 C 10.6094,4.14041 10.3281,4.00369 10.0391,3.98807 Z"); - + // 主Path:扬声器 + 声波线 var group = new GeometryGroup(); group.Children.Add(speakerGeometry); group.Children.Add(wave1Geometry); VolumeIconPath.Data = group; - + // 隐藏第二个Path VolumeIconPath2.Visibility = Visibility.Collapsed; } @@ -688,10 +688,10 @@ namespace Ink_Canvas.Windows private void ExpandPanel() { if (_isExpanded) return; - + _isExpanded = true; UpdateArrowRotation(); - + var animation = (Storyboard)Resources["ExpandAnimation"]; var doubleAnimation = animation.Children[0] as DoubleAnimation; doubleAnimation.From = PanelTransform.X; @@ -702,10 +702,10 @@ namespace Ink_Canvas.Windows private void CollapsePanel() { if (!_isExpanded) return; - + _isExpanded = false; UpdateArrowRotation(); - + var animation = (Storyboard)Resources["CollapseAnimation"]; var doubleAnimation = animation.Children[0] as DoubleAnimation; doubleAnimation.From = PanelTransform.X; @@ -771,7 +771,7 @@ namespace Ink_Canvas.Windows private void ContentBorder_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.OriginalSource is Slider) return; // 如果点击的是滑块,不处理拖动 - + _isDragging = true; _dragStartPoint = e.GetPosition(MainCanvas); ContentBorder.CaptureMouse(); @@ -781,16 +781,16 @@ namespace Ink_Canvas.Windows private void ContentBorder_MouseMove(object sender, MouseEventArgs e) { if (!_isDragging) return; - + Point currentPoint = e.GetPosition(MainCanvas); double deltaX = currentPoint.X - _dragStartPoint.X; - + // 计算新位置 double newX = PanelTransform.X + deltaX; - + // 限制拖动范围 newX = Math.Max(0, Math.Min(_collapsedOffset, newX)); - + PanelTransform.X = newX; _dragStartPoint = currentPoint; } @@ -798,10 +798,10 @@ namespace Ink_Canvas.Windows private void ContentBorder_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (!_isDragging) return; - + _isDragging = false; ContentBorder.ReleaseMouseCapture(); - + // 判断是否超过一半 if (PanelTransform.X < _collapsedOffset / 2) { @@ -816,7 +816,7 @@ namespace Ink_Canvas.Windows private void ContentBorder_TouchDown(object sender, TouchEventArgs e) { if (e.OriginalSource is Slider) return; - + _isDragging = true; _dragStartPoint = e.GetTouchPoint(MainCanvas).Position; e.Handled = true; @@ -825,13 +825,13 @@ namespace Ink_Canvas.Windows private void ContentBorder_TouchMove(object sender, TouchEventArgs e) { if (!_isDragging) return; - + Point currentPoint = e.GetTouchPoint(MainCanvas).Position; double deltaX = currentPoint.X - _dragStartPoint.X; - + double newX = PanelTransform.X + deltaX; newX = Math.Max(0, Math.Min(_collapsedOffset, newX)); - + PanelTransform.X = newX; _dragStartPoint = currentPoint; } @@ -839,9 +839,9 @@ namespace Ink_Canvas.Windows private void ContentBorder_TouchUp(object sender, TouchEventArgs e) { if (!_isDragging) return; - + _isDragging = false; - + if (PanelTransform.X < _collapsedOffset / 2) { ExpandPanel(); @@ -874,15 +874,15 @@ namespace Ink_Canvas.Windows private void VolumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) { if (!IsLoaded) return; - + try { float volume = (float)(e.NewValue / 100.0); SetVolume(volume); - + // 更新文本显示 VolumeValueText.Text = $"{(int)e.NewValue}%"; - + // 如果音量大于0,取消静音 if (e.NewValue > 0) { @@ -892,7 +892,7 @@ namespace Ink_Canvas.Windows SetMute(false); } } - + // 更新图标(根据当前音量和静音状态) bool currentMute = GetMute(); UpdateVolumeIcon(currentMute, volume); @@ -924,21 +924,21 @@ namespace Ink_Canvas.Windows private async void InsertImageSelectFileButton_Click(object sender, RoutedEventArgs e) { if (_mainWindow == null) return; - + try { var dialog = new OpenFileDialog { Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif" }; - + if (dialog.ShowDialog() == true) { string filePath = dialog.FileName; - - var createImageMethod = _mainWindow.GetType().GetMethod("CreateAndCompressImageAsync", + + var createImageMethod = _mainWindow.GetType().GetMethod("CreateAndCompressImageAsync", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); - + if (createImageMethod != null) { var imageTask = createImageMethod.Invoke(_mainWindow, new object[] { filePath }) as System.Threading.Tasks.Task; @@ -967,12 +967,12 @@ namespace Ink_Canvas.Windows private async void InsertImageScreenshotButton_Click(object sender, RoutedEventArgs e) { if (_mainWindow == null) return; - + try { - var captureScreenshotMethod = _mainWindow.GetType().GetMethod("CaptureScreenshotAndInsert", + var captureScreenshotMethod = _mainWindow.GetType().GetMethod("CaptureScreenshotAndInsert", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); - + if (captureScreenshotMethod != null) { var task = captureScreenshotMethod.Invoke(_mainWindow, null) as System.Threading.Tasks.Task; @@ -998,9 +998,9 @@ namespace Ink_Canvas.Windows try { if (_mainWindow == null) return; - + System.Windows.Controls.InkCanvas inkCanvas = null; - var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", + var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (inkCanvasField != null) { @@ -1008,13 +1008,13 @@ namespace Ink_Canvas.Windows } if (inkCanvas == null) { - var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", + var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); inkCanvas = inkCanvasProperty?.GetValue(_mainWindow) as System.Windows.Controls.InkCanvas; } - + if (inkCanvas == null) return; - + System.Windows.Controls.Image lastScreenshot = null; foreach (System.Windows.Controls.Image img in inkCanvas.Children.OfType()) { @@ -1023,17 +1023,17 @@ namespace Ink_Canvas.Windows lastScreenshot = img; } } - + if (lastScreenshot == null) return; - + string screenshotFilePath = await SaveScreenshotToFile(lastScreenshot); - + if (string.IsNullOrEmpty(screenshotFilePath)) { LogHelper.WriteLogToFile("保存截图文件失败", LogHelper.LogType.Warning); return; } - + lastScreenshot.Tag = screenshotFilePath; await ManageScreenshotInPPT(lastScreenshot, screenshotFilePath); } @@ -1048,7 +1048,7 @@ namespace Ink_Canvas.Windows try { if (image?.Source == null) return null; - + string savePath = null; var settingsProperty = _mainWindow.GetType().GetProperty("Settings"); if (settingsProperty != null) @@ -1075,35 +1075,35 @@ namespace Ink_Canvas.Windows } } } - + if (string.IsNullOrEmpty(savePath)) { LogHelper.WriteLogToFile("无法获取AutoSavedStrokesLocation", LogHelper.LogType.Warning); return null; } - + if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } - + string timestamp = image.Name; string filePath = Path.Combine(savePath, timestamp + ".png"); - + await Application.Current.Dispatcher.InvokeAsync(() => { if (image.Source is BitmapSource bitmapSource) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); - + using (var fileStream = new FileStream(filePath, FileMode.Create)) { encoder.Save(fileStream); } } }); - + return filePath; } catch (Exception ex) @@ -1116,7 +1116,7 @@ namespace Ink_Canvas.Windows private async System.Threading.Tasks.Task ManageScreenshotInPPT(System.Windows.Controls.Image image, string filePath) { if (_mainWindow == null || image == null || string.IsNullOrEmpty(filePath)) return; - + await Application.Current.Dispatcher.InvokeAsync(() => { try @@ -1124,10 +1124,10 @@ namespace Ink_Canvas.Windows int currentSlideNumber = 0; try { - var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", + var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); var pptManager = pptManagerProperty?.GetValue(_mainWindow); - + if (pptManager != null) { var isInSlideShowProperty = pptManager.GetType().GetProperty("IsInSlideShow"); @@ -1140,7 +1140,7 @@ namespace Ink_Canvas.Windows isInSlideShow = (bool)result; } } - + if (isInSlideShow) { var getCurrentSlideNumberMethod = pptManager.GetType().GetMethod("GetCurrentSlideNumber"); @@ -1159,18 +1159,18 @@ namespace Ink_Canvas.Windows { LogHelper.WriteLogToFile($"获取当前PPT页面编号失败: {ex.Message}", LogHelper.LogType.Warning); } - + if (currentSlideNumber > 0 && !string.IsNullOrEmpty(filePath)) { _pptImages[image] = currentSlideNumber; - + if (!_pptImagePaths.ContainsKey(currentSlideNumber)) { _pptImagePaths[currentSlideNumber] = new List(); } _pptImagePaths[currentSlideNumber].Add(filePath); SavePPTImagePaths(currentSlideNumber); - + LogHelper.WriteLogToFile($"截图已关联到PPT页面{currentSlideNumber}: {filePath}"); } else if (currentSlideNumber > 0) @@ -1188,7 +1188,7 @@ namespace Ink_Canvas.Windows private async System.Threading.Tasks.Task InsertImageToMainWindow(System.Windows.Controls.Image image, string originalFilePath = null, bool saveToJson = true) { if (_mainWindow == null || image == null) return; - + // 确保在UI线程上执行 await Application.Current.Dispatcher.InvokeAsync(() => { @@ -1203,23 +1203,23 @@ namespace Ink_Canvas.Windows image.Focusable = false; System.Windows.Controls.InkCanvas inkCanvas = null; - var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", + var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (inkCanvasField != null) { inkCanvas = inkCanvasField.GetValue(_mainWindow) as System.Windows.Controls.InkCanvas; } - + if (inkCanvas == null) { - var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", + var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (inkCanvasProperty != null) { inkCanvas = inkCanvasProperty.GetValue(_mainWindow) as System.Windows.Controls.InkCanvas; } } - + if (inkCanvas == null) { LogHelper.WriteLogToFile("无法获取inkCanvas", LogHelper.LogType.Error); @@ -1227,7 +1227,7 @@ namespace Ink_Canvas.Windows } // 初始化InkCanvas选择设置 - var initializeInkCanvasSelectionSettingsMethod = _mainWindow.GetType().GetMethod("InitializeInkCanvasSelectionSettings", + var initializeInkCanvasSelectionSettingsMethod = _mainWindow.GetType().GetMethod("InitializeInkCanvasSelectionSettings", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); initializeInkCanvasSelectionSettingsMethod?.Invoke(_mainWindow, null); @@ -1235,10 +1235,10 @@ namespace Ink_Canvas.Windows int currentSlideNumber = 0; try { - var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", + var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); var pptManager = pptManagerProperty?.GetValue(_mainWindow); - + if (pptManager != null) { var isInSlideShowProperty = pptManager.GetType().GetProperty("IsInSlideShow"); @@ -1251,7 +1251,7 @@ namespace Ink_Canvas.Windows isInSlideShow = (bool)result; } } - + if (isInSlideShow) { var getCurrentSlideNumberMethod = pptManager.GetType().GetMethod("GetCurrentSlideNumber"); @@ -1270,19 +1270,19 @@ namespace Ink_Canvas.Windows { LogHelper.WriteLogToFile($"获取当前PPT页面编号失败: {ex.Message}", LogHelper.LogType.Warning); } - + // 如果在PPT模式下,记录图片和页面编号的关联,并保存图片路径 if (currentSlideNumber > 0 && !string.IsNullOrEmpty(originalFilePath) && saveToJson) { _pptImages[image] = currentSlideNumber; - + // 添加到页面图片路径列表 if (!_pptImagePaths.ContainsKey(currentSlideNumber)) { _pptImagePaths[currentSlideNumber] = new List(); } _pptImagePaths[currentSlideNumber].Add(originalFilePath); - + // 保存图片路径到JSON文件 SavePPTImagePaths(currentSlideNumber); } @@ -1303,17 +1303,17 @@ namespace Ink_Canvas.Windows try { // 初始化TransformGroup - var initializeTransformMethod = _mainWindow.GetType().GetMethod("InitializeElementTransform", + var initializeTransformMethod = _mainWindow.GetType().GetMethod("InitializeElementTransform", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); initializeTransformMethod?.Invoke(_mainWindow, new object[] { image }); // 居中缩放 - var centerMethod = _mainWindow.GetType().GetMethod("CenterAndScaleElement", + var centerMethod = _mainWindow.GetType().GetMethod("CenterAndScaleElement", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); centerMethod?.Invoke(_mainWindow, new object[] { image }); // 绑定事件处理器 - var bindEventsMethod = _mainWindow.GetType().GetMethod("BindElementEvents", + var bindEventsMethod = _mainWindow.GetType().GetMethod("BindElementEvents", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); bindEventsMethod?.Invoke(_mainWindow, new object[] { image }); @@ -1327,7 +1327,7 @@ namespace Ink_Canvas.Windows }; // 提交历史记录 - var timeMachineProperty = _mainWindow.GetType().GetProperty("timeMachine", + var timeMachineProperty = _mainWindow.GetType().GetProperty("timeMachine", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var timeMachine = timeMachineProperty?.GetValue(_mainWindow); if (timeMachine != null) @@ -1337,15 +1337,15 @@ namespace Ink_Canvas.Windows } // 切换到选择模式 - var setModeMethod = _mainWindow.GetType().GetMethod("SetCurrentToolMode", + var setModeMethod = _mainWindow.GetType().GetMethod("SetCurrentToolMode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); setModeMethod?.Invoke(_mainWindow, new object[] { System.Windows.Controls.InkCanvasEditingMode.Select }); - - var updateModeMethod = _mainWindow.GetType().GetMethod("UpdateCurrentToolMode", + + var updateModeMethod = _mainWindow.GetType().GetMethod("UpdateCurrentToolMode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); updateModeMethod?.Invoke(_mainWindow, new object[] { "select" }); - - var hidePanelsMethod = _mainWindow.GetType().GetMethod("HideSubPanels", + + var hidePanelsMethod = _mainWindow.GetType().GetMethod("HideSubPanels", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); hidePanelsMethod?.Invoke(_mainWindow, new object[] { "select" }); } @@ -1368,39 +1368,39 @@ namespace Ink_Canvas.Windows try { if (_mainWindow == null) return null; - + // 获取PPTInkManager - var singlePPTInkManagerField = _mainWindow.GetType().GetField("_singlePPTInkManager", + var singlePPTInkManagerField = _mainWindow.GetType().GetField("_singlePPTInkManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var singlePPTInkManager = singlePPTInkManagerField?.GetValue(_mainWindow); - + if (singlePPTInkManager != null) { // 使用反射获取AutoSaveLocation var autoSaveLocationProperty = singlePPTInkManager.GetType().GetProperty("AutoSaveLocation"); var autoSaveLocation = autoSaveLocationProperty?.GetValue(singlePPTInkManager) as string; - + if (!string.IsNullOrEmpty(autoSaveLocation)) { // 获取PPTManager以获取当前演示文稿信息 - var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", + var pptManagerProperty = _mainWindow.GetType().GetProperty("PPTManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); var pptManager = pptManagerProperty?.GetValue(_mainWindow); - + if (pptManager != null) { // 尝试获取当前演示文稿,使用重试机制 Microsoft.Office.Interop.PowerPoint.Presentation presentation = null; - + // 首先尝试使用 CurrentPresentation 属性(可能是缓存的) try { - var currentPresentationProperty = pptManager.GetType().GetProperty("CurrentPresentation", + var currentPresentationProperty = pptManager.GetType().GetProperty("CurrentPresentation", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); presentation = currentPresentationProperty?.GetValue(pptManager) as Microsoft.Office.Interop.PowerPoint.Presentation; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } - + // 如果 CurrentPresentation 不可用,尝试 GetCurrentActivePresentation if (presentation == null) { @@ -1411,7 +1411,7 @@ namespace Ink_Canvas.Windows } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } } - + if (presentation != null) { try @@ -1421,7 +1421,7 @@ namespace Ink_Canvas.Windows { return null; } - + // 尝试访问对象以验证其有效性 try { @@ -1433,7 +1433,7 @@ namespace Ink_Canvas.Windows // COM对象已失效,静默返回 return null; } - + // 立即生成演示文稿ID(在对象失效前) string presentationId = GeneratePresentationId(presentation); if (string.IsNullOrEmpty(presentationId) || presentationId.StartsWith("unknown_") || presentationId.StartsWith("invalid_") || presentationId.StartsWith("com_error_")) @@ -1441,7 +1441,7 @@ namespace Ink_Canvas.Windows // 生成ID失败,返回null而不是抛出异常 return null; } - + return Path.Combine(autoSaveLocation, "Auto Saved - Presentations", presentationId); } catch (System.Runtime.InteropServices.InvalidComObjectException) @@ -1457,7 +1457,7 @@ namespace Ink_Canvas.Windows catch (Exception ex) { // 其他异常,只记录非COM相关异常 - if (!(ex is System.Runtime.InteropServices.InvalidComObjectException) && + if (!(ex is System.Runtime.InteropServices.InvalidComObjectException) && !(ex is System.Runtime.InteropServices.COMException)) { LogHelper.WriteLogToFile($"获取PPT文件夹路径时发生非COM异常: {ex.Message}", LogHelper.LogType.Warning); @@ -1482,13 +1482,13 @@ namespace Ink_Canvas.Windows catch (Exception ex) { // 只记录非COM相关异常 - if (!(ex is System.Runtime.InteropServices.InvalidComObjectException) && + if (!(ex is System.Runtime.InteropServices.InvalidComObjectException) && !(ex is System.Runtime.InteropServices.COMException)) { LogHelper.WriteLogToFile($"获取PPT文件夹路径失败: {ex.Message}", LogHelper.LogType.Error); } } - + return null; } @@ -1501,7 +1501,7 @@ namespace Ink_Canvas.Windows { return $"unknown_{DateTime.Now.Ticks}"; } - + try { // 检查COM对象是否仍然有效 @@ -1509,7 +1509,7 @@ namespace Ink_Canvas.Windows { return $"unknown_{DateTime.Now.Ticks}"; } - + // 验证COM对象有效性 try { @@ -1521,12 +1521,12 @@ namespace Ink_Canvas.Windows // COM对象已失效 return $"unknown_{DateTime.Now.Ticks}"; } - + // 逐个访问属性,每个都进行异常处理 string presentationName = null; string presentationPath = null; int slidesCount = 0; - + try { presentationName = presentation.Name; @@ -1539,7 +1539,7 @@ namespace Ink_Canvas.Windows { return $"unknown_{DateTime.Now.Ticks}"; } - + try { presentationPath = presentation.FullName; @@ -1552,7 +1552,7 @@ namespace Ink_Canvas.Windows { return $"unknown_{DateTime.Now.Ticks}"; } - + try { slidesCount = presentation.Slides.Count; @@ -1565,7 +1565,7 @@ namespace Ink_Canvas.Windows { return $"unknown_{DateTime.Now.Ticks}"; } - + var fileHash = GetFileHash(presentationPath); return $"{presentationName}_{slidesCount}_{fileHash}"; } @@ -1616,21 +1616,21 @@ namespace Ink_Canvas.Windows try { if (slideIndex <= 0 || !_pptImagePaths.ContainsKey(slideIndex)) return; - + var folderPath = GetPresentationFolderPath(); if (string.IsNullOrEmpty(folderPath)) return; - + if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } - + var jsonFilePath = Path.Combine(folderPath, slideIndex.ToString("0000") + ".images.json"); var imagePaths = _pptImagePaths[slideIndex]; - + string json = JsonConvert.SerializeObject(imagePaths, Formatting.Indented); File.WriteAllText(jsonFilePath, json); - + LogHelper.WriteLogToFile($"已保存第{slideIndex}页图片路径到JSON: {jsonFilePath}"); } catch (Exception ex) @@ -1647,18 +1647,18 @@ namespace Ink_Canvas.Windows try { if (slideIndex <= 0) return new List(); - + var folderPath = GetPresentationFolderPath(); - if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath)) + if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath)) return new List(); - + var jsonFilePath = Path.Combine(folderPath, slideIndex.ToString("0000") + ".images.json"); - if (!File.Exists(jsonFilePath)) + if (!File.Exists(jsonFilePath)) return new List(); - + string json = File.ReadAllText(jsonFilePath); var imagePaths = JsonConvert.DeserializeObject>(json); - + return imagePaths ?? new List(); } catch (Exception ex) @@ -1676,13 +1676,13 @@ namespace Ink_Canvas.Windows try { if (_mainWindow == null || slideIndex <= 0) return; - + var imagePaths = LoadPPTImagePaths(slideIndex); if (imagePaths == null || imagePaths.Count == 0) return; - + // 获取inkCanvas,检查是否已有图片 System.Windows.Controls.InkCanvas inkCanvas = null; - var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", + var inkCanvasField = _mainWindow.GetType().GetField("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (inkCanvasField != null) { @@ -1690,13 +1690,13 @@ namespace Ink_Canvas.Windows } if (inkCanvas == null) { - var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", + var inkCanvasProperty = _mainWindow.GetType().GetProperty("inkCanvas", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); inkCanvas = inkCanvasProperty?.GetValue(_mainWindow) as System.Windows.Controls.InkCanvas; } - + if (inkCanvas == null) return; - + // 检查已存在的图片路径(通过Tag) var existingImagePaths = new HashSet(); foreach (System.Windows.Controls.Image existingImage in inkCanvas.Children.OfType()) @@ -1706,17 +1706,17 @@ namespace Ink_Canvas.Windows existingImagePaths.Add(tagPath); } } - + // 使用反射调用MainWindow的CreateAndCompressImageAsync方法 - var createImageMethod = _mainWindow.GetType().GetMethod("CreateAndCompressImageAsync", + var createImageMethod = _mainWindow.GetType().GetMethod("CreateAndCompressImageAsync", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); - + if (createImageMethod == null) { LogHelper.WriteLogToFile("无法找到CreateAndCompressImageAsync方法", LogHelper.LogType.Warning); return; } - + foreach (var imagePath in imagePaths) { try @@ -1726,13 +1726,13 @@ namespace Ink_Canvas.Windows { continue; } - + if (!File.Exists(imagePath)) { LogHelper.WriteLogToFile($"图片文件不存在: {imagePath}", LogHelper.LogType.Warning); continue; } - + var imageTask = createImageMethod.Invoke(_mainWindow, new object[] { imagePath }) as System.Threading.Tasks.Task; if (imageTask != null) { @@ -1741,7 +1741,7 @@ namespace Ink_Canvas.Windows { // 保存原始文件路径到Tag image.Tag = imagePath; - + // 插入图片(不保存路径,因为已经存在) await InsertImageToMainWindow(image, imagePath, false); } @@ -1767,14 +1767,14 @@ namespace Ink_Canvas.Windows try { if (_mainWindow == null) return; - + var folderPath = GetPresentationFolderPath(); - if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath)) + if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath)) return; - + // 清空现有数据 _pptImagePaths.Clear(); - + // 查找所有图片JSON文件 var jsonFiles = Directory.GetFiles(folderPath, "*.images.json"); foreach (var jsonFile in jsonFiles) @@ -1783,7 +1783,7 @@ namespace Ink_Canvas.Windows { var fileName = Path.GetFileNameWithoutExtension(jsonFile); fileName = fileName.Replace(".images", ""); // 移除.images后缀 - + if (int.TryParse(fileName, out int slideIndex) && slideIndex > 0) { var imagePaths = LoadPPTImagePaths(slideIndex); @@ -1798,7 +1798,7 @@ namespace Ink_Canvas.Windows LogHelper.WriteLogToFile($"加载图片路径文件失败: {jsonFile}, 错误: {ex.Message}", LogHelper.LogType.Error); } } - + LogHelper.WriteLogToFile($"已加载{_pptImagePaths.Count}个页面的图片路径"); } catch (Exception ex) diff --git a/Ink Canvas/Windows/PPTTimeCapsule.xaml.cs b/Ink Canvas/Windows/PPTTimeCapsule.xaml.cs index 9cee0dcd..53984d7c 100644 --- a/Ink Canvas/Windows/PPTTimeCapsule.xaml.cs +++ b/Ink Canvas/Windows/PPTTimeCapsule.xaml.cs @@ -1,10 +1,6 @@ using Ink_Canvas.Helpers; using Microsoft.Win32; -using Newtonsoft.Json; using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Timers; using System.Windows; using System.Windows.Controls; @@ -12,7 +8,6 @@ using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Threading; -using File = System.IO.File; namespace Ink_Canvas.Windows { @@ -22,10 +17,10 @@ namespace Ink_Canvas.Windows public partial class PPTTimeCapsule : UserControl, IDisposable { private System.Timers.Timer timeUpdateTimer; - private System.Timers.Timer countdownUpdateTimer; + private System.Timers.Timer countdownUpdateTimer; private DateTime lastTime = DateTime.MinValue; - private TimerControl parentControl; - private bool wasTimerRunning = false; + private TimerControl parentControl; + private bool wasTimerRunning = false; private bool isOvertime = false; private Storyboard capsuleExpandStoryboard; private Storyboard capsuleShrinkStoryboard; @@ -39,10 +34,10 @@ namespace Ink_Canvas.Windows InitializeComponent(); InitializeTimers(); ApplyTheme(); - + // 监听主题变化 SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged; - + Loaded += PPTTimeCapsule_Loaded; Unloaded += PPTTimeCapsule_Unloaded; IsVisibleChanged += PPTTimeCapsule_IsVisibleChanged; @@ -88,7 +83,7 @@ namespace Ink_Canvas.Windows // 时间更新定时器(每秒更新) timeUpdateTimer = new System.Timers.Timer(1000); timeUpdateTimer.Elapsed += TimeUpdateTimer_Elapsed; - + // 倒计时更新定时器 countdownUpdateTimer = new System.Timers.Timer(250); countdownUpdateTimer.Elapsed += CountdownUpdateTimer_Elapsed; @@ -158,49 +153,49 @@ namespace Ink_Canvas.Windows private void UpdateTimeDisplay() { DateTime now = DateTime.Now; - + // 检查小时是否改变 - if (lastTime != DateTime.MinValue && lastTime.Hour != now.Hour) - { - // 先更新数字内容 - SetDigitDisplay("Hour1Display", now.Hour / 10); - SetDigitDisplay("Hour2Display", now.Hour % 10); - - // 重置Transform位置到上方 - HourContentTransform.Y = -40; - HourPanel.Opacity = 0; - - // 播放小时滚动动画:从上方滚入 - PlayHourScrollAnimation(); - } - else if (lastTime == DateTime.MinValue) - { - // 首次加载,直接更新显示 - SetDigitDisplay("Hour1Display", now.Hour / 10); - SetDigitDisplay("Hour2Display", now.Hour % 10); - } - + if (lastTime != DateTime.MinValue && lastTime.Hour != now.Hour) + { + // 先更新数字内容 + SetDigitDisplay("Hour1Display", now.Hour / 10); + SetDigitDisplay("Hour2Display", now.Hour % 10); + + // 重置Transform位置到上方 + HourContentTransform.Y = -40; + HourPanel.Opacity = 0; + + // 播放小时滚动动画:从上方滚入 + PlayHourScrollAnimation(); + } + else if (lastTime == DateTime.MinValue) + { + // 首次加载,直接更新显示 + SetDigitDisplay("Hour1Display", now.Hour / 10); + SetDigitDisplay("Hour2Display", now.Hour % 10); + } + // 检查分钟是否改变 - if (lastTime != DateTime.MinValue && lastTime.Minute != now.Minute) - { - // 先更新数字内容 - SetDigitDisplay("Minute1Display", now.Minute / 10); - SetDigitDisplay("Minute2Display", now.Minute % 10); - - // 重置Transform位置到上方 - MinuteContentTransform.Y = -40; - MinutePanel.Opacity = 0; - - // 播放分钟滚动动画:从上方滚入 - PlayMinuteScrollAnimation(); - } - else if (lastTime == DateTime.MinValue) - { - // 首次加载,直接更新显示 - SetDigitDisplay("Minute1Display", now.Minute / 10); - SetDigitDisplay("Minute2Display", now.Minute % 10); - } - + if (lastTime != DateTime.MinValue && lastTime.Minute != now.Minute) + { + // 先更新数字内容 + SetDigitDisplay("Minute1Display", now.Minute / 10); + SetDigitDisplay("Minute2Display", now.Minute % 10); + + // 重置Transform位置到上方 + MinuteContentTransform.Y = -40; + MinutePanel.Opacity = 0; + + // 播放分钟滚动动画:从上方滚入 + PlayMinuteScrollAnimation(); + } + else if (lastTime == DateTime.MinValue) + { + // 首次加载,直接更新显示 + SetDigitDisplay("Minute1Display", now.Minute / 10); + SetDigitDisplay("Minute2Display", now.Minute % 10); + } + lastTime = now; } @@ -210,7 +205,7 @@ namespace Ink_Canvas.Windows var scrollAnimation = (Storyboard)Resources["HourScrollAnimation"]; scrollAnimation.Begin(); } - + private void PlayMinuteScrollAnimation() { // 新时间从上方滚入(-25到0) @@ -301,12 +296,12 @@ namespace Ink_Canvas.Windows bool wasRunning = wasTimerRunning; wasTimerRunning = false; CountdownPanel.Visibility = Visibility.Collapsed; - + // 重置超时状态 isOvertime = false; // 根据主题恢复倒计时文本颜色 ApplyTheme(); - + // 播放胶囊缩短动画 if (wasRunning) { @@ -320,7 +315,7 @@ namespace Ink_Canvas.Windows // 检查计时器是否正在运行 bool isRunning = parentControl.IsTimerRunning; - + // 如果状态改变,更新UI if (isRunning != wasTimerRunning) { @@ -362,33 +357,33 @@ namespace Ink_Canvas.Windows var timeSpan = remainingTime.Value; bool isOvertimeMode = timeSpan.TotalSeconds < 0; - + // 更新倒计时文本 UpdateCountdownText(timeSpan, isOvertimeMode); - + // 根据文本内容动态调整胶囊宽度 AdjustCapsuleWidthToContent(); } - + /// /// 更新倒计时文本内容 /// private void UpdateCountdownText(TimeSpan? timeSpan = null, bool? isOvertimeMode = null) { if (CountdownText == null || parentControl == null) return; - + if (!timeSpan.HasValue) { var remainingTime = parentControl.GetRemainingTime(); if (!remainingTime.HasValue) return; timeSpan = remainingTime.Value; } - + if (!isOvertimeMode.HasValue) { isOvertimeMode = timeSpan.Value.TotalSeconds < 0; } - + // 处理超时状态 if (isOvertimeMode.Value) { @@ -397,14 +392,14 @@ namespace Ink_Canvas.Windows isOvertime = true; OnTimerOvertime(); } - + // 确保倒计时文本为红色(如果启用了超时红色文本设置) var mainWindow = Application.Current.MainWindow as MainWindow; if (mainWindow != null && MainWindow.Settings.RandSettings?.EnableOvertimeRedText == true) { CountdownText.Foreground = new SolidColorBrush(Colors.Red); } - + // 显示超时时间 var overtimeSpan = -timeSpan.Value; if (overtimeSpan.TotalHours >= 1) @@ -456,14 +451,14 @@ namespace Ink_Canvas.Windows } } } - + /// /// 根据内容动态调整胶囊宽度 /// private void AdjustCapsuleWidthToContent() { if (MainCapsule == null || !wasTimerRunning || CountdownText == null) return; - + try { // 检查文本是否改变(格式变化可能导致宽度变化) @@ -473,12 +468,12 @@ namespace Ink_Canvas.Windows // 文本未改变,不需要调整 return; } - + lastCountdownText = currentText; - + double currentWidth = MainCapsule.ActualWidth; double targetWidth = CalculateTargetWidth(); - + // 如果当前宽度与目标宽度差异较大(超过2像素),则调整 if (Math.Abs(currentWidth - targetWidth) > 2) { @@ -496,25 +491,25 @@ namespace Ink_Canvas.Windows { capsuleShrinkStoryboard.Stop(); } - + // 创建新的动画 var animation = new DoubleAnimation { From = currentWidth, To = targetWidth, Duration = new Duration(TimeSpan.FromMilliseconds(targetWidth > currentWidth ? 600 : 800)), - EasingFunction = targetWidth > currentWidth + EasingFunction = targetWidth > currentWidth ? new BackEase { EasingMode = EasingMode.EaseOut, Amplitude = 0.4 } : new BackEase { EasingMode = EasingMode.EaseOut, Amplitude = 0.2 } }; - + var storyboard = new Storyboard(); Storyboard.SetTarget(animation, MainCapsule); Storyboard.SetTargetProperty(animation, new PropertyPath(FrameworkElement.WidthProperty)); storyboard.Children.Add(animation); currentWidthAnimation = storyboard; storyboard.Begin(); - + storyboard.Completed += (o, args) => { storyboard.Remove(); @@ -542,22 +537,22 @@ namespace Ink_Canvas.Windows { originalCapsuleWidth = MainCapsule.ActualWidth > 0 ? MainCapsule.ActualWidth : 120; } - + // 停止当前动画 if (currentWidthAnimation != null) { currentWidthAnimation.Stop(); currentWidthAnimation = null; } - + // 根据倒计时文本的实际宽度动态计算目标宽度 double targetWidth = CalculateTargetWidth(); - + if (capsuleExpandStoryboard == null) { capsuleExpandStoryboard = (Storyboard)Resources["CapsuleExpandAnimation"]; } - + if (capsuleExpandStoryboard != null) { // 设置动画的目标值 @@ -567,7 +562,7 @@ namespace Ink_Canvas.Windows animation.From = MainCapsule.ActualWidth; animation.To = targetWidth; } - + capsuleExpandStoryboard.Begin(); } } @@ -577,7 +572,7 @@ namespace Ink_Canvas.Windows LogHelper.WriteLogToFile($"播放胶囊伸长动画失败: {ex.Message}", LogHelper.LogType.Error); } } - + /// /// 根据倒计时文本的实际宽度计算目标宽度 /// @@ -588,26 +583,26 @@ namespace Ink_Canvas.Windows // 如果倒计时文本不可用,使用估算值 return originalCapsuleWidth + 80; } - + // 测量倒计时文本的实际宽度 CountdownText.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); double countdownTextWidth = CountdownText.DesiredSize.Width; - + // 测量时间显示面板的宽度 TimeDisplayPanel.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); double timeDisplayWidth = TimeDisplayPanel.DesiredSize.Width; - + double targetWidth = timeDisplayWidth + countdownTextWidth + 8 + 32; - + // 确保最小宽度不小于原始宽度 if (targetWidth < originalCapsuleWidth) { targetWidth = originalCapsuleWidth; } - + return targetWidth; } - + private void PlayCapsuleShrinkAnimation() { try @@ -620,15 +615,15 @@ namespace Ink_Canvas.Windows currentWidthAnimation.Stop(); currentWidthAnimation = null; } - + // 重置文本跟踪 lastCountdownText = ""; - + if (capsuleShrinkStoryboard == null) { capsuleShrinkStoryboard = (Storyboard)Resources["CapsuleShrinkAnimation"]; } - + if (capsuleShrinkStoryboard != null) { // 设置动画的目标值 @@ -638,7 +633,7 @@ namespace Ink_Canvas.Windows animation.From = MainCapsule.ActualWidth; animation.To = originalCapsuleWidth; } - + capsuleShrinkStoryboard.Begin(); } } @@ -670,7 +665,7 @@ namespace Ink_Canvas.Windows Dispatcher.BeginInvoke(new Action(() => OnTimerCompleted()), DispatcherPriority.Normal); return; } - + // 停止倒计时 StopCountdown(); } @@ -682,31 +677,31 @@ namespace Ink_Canvas.Windows if (mainWindow != null) { mainWindow.AdjustTimerContainerSize(); - + // 显示主计时器窗口 var timerContainer = mainWindow.FindName("TimerContainer") as FrameworkElement; if (timerContainer != null) { timerContainer.Visibility = Visibility.Visible; } - + // 隐藏最小化计时器容器 var minimizedContainer = mainWindow.FindName("MinimizedTimerContainer") as FrameworkElement; if (minimizedContainer != null) { minimizedContainer.Visibility = Visibility.Collapsed; } - + if (mainWindow.TimerControl != null) { mainWindow.TimerControl.UpdateActivityTime(); - + mainWindow.TimerControl.CloseRequested -= TimerControl_CloseRequested; mainWindow.TimerControl.CloseRequested += TimerControl_CloseRequested; } } } - + private void TimerControl_CloseRequested(object sender, EventArgs e) { // 当计时器窗口关闭时,隐藏TimerContainer @@ -718,7 +713,7 @@ namespace Ink_Canvas.Windows { timerContainer.Visibility = Visibility.Collapsed; } - + var minimizedContainer = mainWindow.FindName("MinimizedTimerContainer") as FrameworkElement; if (minimizedContainer != null) { @@ -828,7 +823,7 @@ namespace Ink_Canvas.Windows /// 获取当前倒计时状态 /// public bool IsCountdownRunning => parentControl != null && parentControl.IsTimerRunning; - + /// /// 获取是否超时 /// diff --git a/Ink Canvas/Windows/PrivacyAgreementWindow.xaml.cs b/Ink Canvas/Windows/PrivacyAgreementWindow.xaml.cs index fff99cd2..32bd359f 100644 --- a/Ink Canvas/Windows/PrivacyAgreementWindow.xaml.cs +++ b/Ink Canvas/Windows/PrivacyAgreementWindow.xaml.cs @@ -64,7 +64,7 @@ namespace Ink_Canvas try { this.Topmost = true; - + Dispatcher.BeginInvoke(new Action(() => { this.Activate(); @@ -74,7 +74,7 @@ namespace Ink_Canvas }), DispatcherPriority.Loaded); string privacyText = null; - + try { var assembly = Assembly.GetExecutingAssembly(); diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/AboutPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/AboutPanel.xaml.cs index 493c72a2..7d56337f 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/AboutPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/AboutPanel.xaml.cs @@ -1,5 +1,5 @@ -using iNKORE.UI.WPF.Helpers; using Ink_Canvas.Helpers; +using iNKORE.UI.WPF.Helpers; using OSVersionExtension; using System; using System.Collections.Generic; @@ -8,7 +8,6 @@ using System.IO; using System.Management; using System.Reflection; using System.Runtime.InteropServices; -using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; @@ -16,7 +15,6 @@ using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; -using Microsoft.Win32; namespace Ink_Canvas.Windows.SettingsViews { @@ -71,7 +69,7 @@ namespace Ink_Canvas.Windows.SettingsViews { var copyright = Assembly.GetExecutingAssembly().GetCustomAttribute(); if (copyright != null && !string.IsNullOrEmpty(copyright.Copyright)) - { + { var copyrightText = copyright.Copyright; AboutCopyright.Text = copyrightText; AboutBottomCopyright.Text = copyrightText.Replace("Copyright ©", "© Copyright") + " 所有"; @@ -93,17 +91,17 @@ namespace Ink_Canvas.Windows.SettingsViews { var assembly = Assembly.GetExecutingAssembly(); var filePath = assembly.Location; - + if (File.Exists(filePath)) { var bt = File.GetCreationTime(filePath); - var m = bt.Month.ToString().PadLeft(2, '0'); - var d = bt.Day.ToString().PadLeft(2, '0'); - var h = bt.Hour.ToString().PadLeft(2, '0'); - var min = bt.Minute.ToString().PadLeft(2, '0'); - var s = bt.Second.ToString().PadLeft(2, '0'); + var m = bt.Month.ToString().PadLeft(2, '0'); + var d = bt.Day.ToString().PadLeft(2, '0'); + var h = bt.Hour.ToString().PadLeft(2, '0'); + var min = bt.Minute.ToString().PadLeft(2, '0'); + var s = bt.Second.ToString().PadLeft(2, '0'); AboutBuildTime.Text = $"{bt.Year}-{m}-{d} {h}:{min}:{s}"; - } + } else { AboutBuildTime.Text = "获取失败"; @@ -122,8 +120,8 @@ namespace Ink_Canvas.Windows.SettingsViews try { var support = TouchTabletDetectHelper.IsTouchEnabled(); - var touchcount = TouchTabletDetectHelper.GetTouchTabletDevices().Count; - + var touchcount = TouchTabletDetectHelper.GetTouchTabletDevices().Count; + Dispatcher.BeginInvoke(() => { if (support) @@ -145,8 +143,8 @@ namespace Ink_Canvas.Windows.SettingsViews } catch (Exception ex) { - Dispatcher.BeginInvoke(() => - AboutTouchTabletText.Text = "检测失败"); + Dispatcher.BeginInvoke(() => + AboutTouchTabletText.Text = "检测失败"); System.Diagnostics.Debug.WriteLine($"检测触摸设备失败: {ex.Message}"); } }); @@ -208,43 +206,43 @@ namespace Ink_Canvas.Windows.SettingsViews try { - ManagementObjectCollection collection; - using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity")) - collection = searcher.Get(); + ManagementObjectCollection collection; + using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity")) + collection = searcher.Get(); - foreach (var device in collection) - { + foreach (var device in collection) + { try { var name = device.GetPropertyValue("Name")?.ToString() ?? ""; var description = device.GetPropertyValue("Description")?.ToString() ?? ""; - + if (string.IsNullOrEmpty(name)) continue; - + var nameLower = name.ToLower(); var descLower = description.ToLower(); - - if (nameLower.Contains("pentablet") || - nameLower.Contains("tablet") || + + if (nameLower.Contains("pentablet") || + nameLower.Contains("tablet") || nameLower.Contains("touch") || nameLower.Contains("digitizer") || descLower.Contains("touch") || descLower.Contains("digitizer")) { - devices.Add(new USBDeviceInfo( - device.GetPropertyValue("DeviceID")?.ToString() ?? "", - device.GetPropertyValue("PNPDeviceID")?.ToString() ?? "", - description - )); + devices.Add(new USBDeviceInfo( + device.GetPropertyValue("DeviceID")?.ToString() ?? "", + device.GetPropertyValue("PNPDeviceID")?.ToString() ?? "", + description + )); } } catch { continue; } - } + } - collection.Dispose(); + collection.Dispose(); } catch (Exception ex) { @@ -271,10 +269,10 @@ namespace Ink_Canvas.Windows.SettingsViews public static DateTimeOffset? GetBuildDateTime(Assembly assembly) { try - { - var path = assembly.Location; - if (string.IsNullOrEmpty(path) || !File.Exists(path)) { + var path = assembly.Location; + if (string.IsNullOrEmpty(path) || !File.Exists(path)) + { return null; } @@ -284,32 +282,32 @@ namespace Ink_Canvas.Windows.SettingsViews fileStream.Position = 0x3C; fileStream.Read(peHeader, 0, 4); var peHeaderOffset = BitConverter.ToUInt32(peHeader, 0); - + fileStream.Position = peHeaderOffset; var signature = new byte[4]; fileStream.Read(signature, 0, 4); - + if (signature[0] != 0x50 || signature[1] != 0x45 || signature[2] != 0x00 || signature[3] != 0x00) { return null; } - + var fileHeader = new byte[Marshal.SizeOf(typeof(_IMAGE_FILE_HEADER))]; fileStream.Read(fileHeader, 0, fileHeader.Length); - + var pinnedBuffer = GCHandle.Alloc(fileHeader, GCHandleType.Pinned); - try - { - var coffHeader = (_IMAGE_FILE_HEADER)Marshal.PtrToStructure(pinnedBuffer.AddrOfPinnedObject(), typeof(_IMAGE_FILE_HEADER)); + try + { + var coffHeader = (_IMAGE_FILE_HEADER)Marshal.PtrToStructure(pinnedBuffer.AddrOfPinnedObject(), typeof(_IMAGE_FILE_HEADER)); var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var buildTime = epoch.AddSeconds(coffHeader.TimeDateStamp); return new DateTimeOffset(buildTime.ToLocalTime()); + } + finally + { + pinnedBuffer.Free(); + } } - finally - { - pinnedBuffer.Free(); - } - } } catch { @@ -412,7 +410,7 @@ namespace Ink_Canvas.Windows.SettingsViews var border = thumb.Template.FindName("ScrollbarThumbEx", thumb); ((Border)border).Background = new SolidColorBrush(Color.FromRgb(138, 138, 138)); } - + private void LinkOfficialWebsite_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { @@ -461,7 +459,7 @@ namespace Ink_Canvas.Windows.SettingsViews System.Diagnostics.Debug.WriteLine($"打开贡献者名单失败: {ex.Message}"); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/AdvancedPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/AdvancedPanel.xaml.cs index 6f0862bd..948829c0 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/AdvancedPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/AdvancedPanel.xaml.cs @@ -1,4 +1,3 @@ -using Ink_Canvas; using iNKORE.UI.WPF.Helpers; using System; using System.Collections.Generic; @@ -170,8 +169,8 @@ namespace Ink_Canvas.Windows.SettingsViews private void SetToggleSwitchState(Border toggleSwitch, bool isOn) { if (toggleSwitch == null) return; - toggleSwitch.Background = isOn - ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) + toggleSwitch.Background = isOn + ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) : (ThemeHelper.IsDarkTheme ? ThemeHelper.GetButtonBackgroundBrush() : new SolidColorBrush(Color.FromRgb(225, 225, 225))); var innerBorder = toggleSwitch.Child as Border; if (innerBorder != null) @@ -574,7 +573,7 @@ namespace Ink_Canvas.Windows.SettingsViews break; } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/AppearancePanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/AppearancePanel.xaml.cs index 9e331498..d571222b 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/AppearancePanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/AppearancePanel.xaml.cs @@ -29,7 +29,7 @@ namespace Ink_Canvas.Windows.SettingsViews IsTopBarNeedNoShadowEffect?.Invoke(this, new RoutedEventArgs()); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/AutomationPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/AutomationPanel.xaml.cs index 4cd5190f..18eaacdb 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/AutomationPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/AutomationPanel.xaml.cs @@ -1,7 +1,6 @@ using System; using System.Windows; using System.Windows.Controls; -using Ink_Canvas.Windows.SettingsViews; using System.Windows.Media; namespace Ink_Canvas.Windows.SettingsViews @@ -185,7 +184,7 @@ namespace Ink_Canvas.Windows.SettingsViews IsTopBarNeedNoShadowEffect?.Invoke(this, new RoutedEventArgs()); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/CanvasAndInkPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/CanvasAndInkPanel.xaml.cs index a8b57c8f..d7812d80 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/CanvasAndInkPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/CanvasAndInkPanel.xaml.cs @@ -1,11 +1,7 @@ -using Ink_Canvas; using iNKORE.UI.WPF.Helpers; using System; -using System.Linq; using System.Windows; using System.Windows.Controls; -using System.Windows.Controls.Primitives; -using System.Windows.Input; using System.Windows.Media; namespace Ink_Canvas.Windows.SettingsViews @@ -156,7 +152,7 @@ namespace Ink_Canvas.Windows.SettingsViews // 自动保存幻灯片墨迹 if (MainWindow.Settings.PowerPointSettings != null) { - SetToggleSwitchState(FindToggleSwitch("ToggleSwitchAutoSaveStrokesInPowerPoint"), + SetToggleSwitchState(FindToggleSwitch("ToggleSwitchAutoSaveStrokesInPowerPoint"), MainWindow.Settings.PowerPointSettings.IsAutoSaveStrokesInPowerPoint); } } @@ -182,8 +178,8 @@ namespace Ink_Canvas.Windows.SettingsViews private void SetToggleSwitchState(Border toggleSwitch, bool isOn) { if (toggleSwitch == null) return; - toggleSwitch.Background = isOn - ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) + toggleSwitch.Background = isOn + ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) : (ThemeHelper.IsDarkTheme ? ThemeHelper.GetButtonBackgroundBrush() : new SolidColorBrush(Color.FromRgb(225, 225, 225))); var innerBorder = toggleSwitch.Child as Border; if (innerBorder != null) @@ -200,9 +196,9 @@ namespace Ink_Canvas.Windows.SettingsViews { var buttons = new[] { "VerySmall", "Small", "Medium", "Large", "VeryLarge" }; var hyperbolaButtons = new[] { "Yes", "No", "Ask" }; - + string[] buttonNames = group == "EraserSize" ? buttons : hyperbolaButtons; - + bool isDarkTheme = ThemeHelper.IsDarkTheme; var selectedBrush = isDarkTheme ? new SolidColorBrush(Color.FromRgb(25, 25, 25)) : new SolidColorBrush(Color.FromRgb(225, 225, 225)); var unselectedBrush = new SolidColorBrush(Colors.Transparent); @@ -664,7 +660,7 @@ namespace Ink_Canvas.Windows.SettingsViews MainWindowSettingsHelper.InvokeSliderValueChanged("InkFadeTimeSlider", value); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/CrashActionPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/CrashActionPanel.xaml.cs index 84768d37..33add5c1 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/CrashActionPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/CrashActionPanel.xaml.cs @@ -29,7 +29,7 @@ namespace Ink_Canvas.Windows.SettingsViews IsTopBarNeedNoShadowEffect?.Invoke(this, new RoutedEventArgs()); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/FloatingBarDnDSettingsPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/FloatingBarDnDSettingsPanel.xaml.cs index 8e3f26ce..915b01d9 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/FloatingBarDnDSettingsPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/FloatingBarDnDSettingsPanel.xaml.cs @@ -144,7 +144,7 @@ namespace Ink_Canvas.Windows.SettingsViews IconSource = FindResource("PenIcon") as DrawingImage, }); } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/GesturesPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/GesturesPanel.xaml.cs index e2f66d79..47d3675f 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/GesturesPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/GesturesPanel.xaml.cs @@ -1,4 +1,3 @@ -using Ink_Canvas; using iNKORE.UI.WPF.Helpers; using System; using System.Collections.Generic; @@ -120,8 +119,8 @@ namespace Ink_Canvas.Windows.SettingsViews private void SetToggleSwitchState(Border toggleSwitch, bool isOn) { if (toggleSwitch == null) return; - toggleSwitch.Background = isOn - ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) + toggleSwitch.Background = isOn + ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) : (ThemeHelper.IsDarkTheme ? ThemeHelper.GetButtonBackgroundBrush() : new SolidColorBrush(Color.FromRgb(225, 225, 225))); var innerBorder = toggleSwitch.Child as Border; if (innerBorder != null) @@ -341,7 +340,7 @@ namespace Ink_Canvas.Windows.SettingsViews break; } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/InkRecognitionPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/InkRecognitionPanel.xaml.cs index 9ec8aa82..5a829ea4 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/InkRecognitionPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/InkRecognitionPanel.xaml.cs @@ -29,7 +29,7 @@ namespace Ink_Canvas.Windows.SettingsViews IsTopBarNeedNoShadowEffect?.Invoke(this, new RoutedEventArgs()); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/LuckyRandomPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/LuckyRandomPanel.xaml.cs index 6dd01a90..117ffaa3 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/LuckyRandomPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/LuckyRandomPanel.xaml.cs @@ -1,8 +1,6 @@ -using Ink_Canvas; using iNKORE.UI.WPF.Helpers; using System; using System.Collections.Generic; -using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; @@ -167,8 +165,8 @@ namespace Ink_Canvas.Windows.SettingsViews private void SetToggleSwitchState(Border toggleSwitch, bool isOn) { if (toggleSwitch == null) return; - toggleSwitch.Background = isOn - ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) + toggleSwitch.Background = isOn + ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) : (ThemeHelper.IsDarkTheme ? ThemeHelper.GetButtonBackgroundBrush() : new SolidColorBrush(Color.FromRgb(225, 225, 225))); var innerBorder = toggleSwitch.Child as Border; if (innerBorder != null) @@ -467,7 +465,7 @@ namespace Ink_Canvas.Windows.SettingsViews MainWindowSettingsHelper.InvokeSliderValueChanged("MLAvoidanceWeightSlider", value); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/MainWindowSettingsHelper.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/MainWindowSettingsHelper.cs index 98cae9d6..34eddb0c 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/MainWindowSettingsHelper.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/MainWindowSettingsHelper.cs @@ -1,4 +1,3 @@ -using Ink_Canvas; using System; using System.Collections.Generic; using System.Linq; @@ -70,7 +69,7 @@ namespace Ink_Canvas.Windows.SettingsViews // 即使找不到控件,也尝试触发事件(可能通过反射调用) var toggledMethodName = toggleSwitchName + "_Toggled"; InvokeMainWindowMethod(toggledMethodName, null, new RoutedEventArgs()); - + // 通知新设置面板同步状态 NotifySettingsPanelsSyncState(toggleSwitchName); return; @@ -87,10 +86,10 @@ namespace Ink_Canvas.Windows.SettingsViews // 触发 Toggled 事件 var toggledMethodName2 = toggleSwitchName + "_Toggled"; InvokeMainWindowMethod(toggledMethodName2, toggleSwitch, new RoutedEventArgs()); - + // 通知新设置面板同步状态 NotifySettingsPanelsSyncState(toggleSwitchName); - + // 检查是否需要更新主题 NotifyThemeUpdateIfNeeded(toggleSwitchName); } @@ -115,18 +114,18 @@ namespace Ink_Canvas.Windows.SettingsViews if (comboBox != null) { comboBox.SelectedItem = selectedItem; - + // 触发 SelectionChanged 事件 var selectionChangedMethodName = comboBoxName + "_SelectionChanged"; InvokeMainWindowMethod(selectionChangedMethodName, comboBox, new System.Windows.Controls.SelectionChangedEventArgs( - System.Windows.Controls.Primitives.Selector.SelectionChangedEvent, - new System.Collections.IList[0], + System.Windows.Controls.Primitives.Selector.SelectionChangedEvent, + new System.Collections.IList[0], new System.Collections.IList[0])); } - + // 通知新设置面板同步状态 NotifySettingsPanelsSyncState(comboBoxName); - + // 检查是否需要更新主题 NotifyThemeUpdateIfNeeded(comboBoxName); } @@ -152,16 +151,16 @@ namespace Ink_Canvas.Windows.SettingsViews { var oldValue = slider.Value; slider.Value = value; - + // 触发 ValueChanged 事件 var valueChangedMethodName = sliderName + "_ValueChanged"; - InvokeMainWindowMethod(valueChangedMethodName, slider, + InvokeMainWindowMethod(valueChangedMethodName, slider, new System.Windows.RoutedPropertyChangedEventArgs(oldValue, value)); } - + // 通知新设置面板同步状态 NotifySettingsPanelsSyncState(sliderName); - + // 检查是否需要更新主题(某些Slider可能影响UI外观) NotifyThemeUpdateIfNeeded(sliderName); } @@ -186,7 +185,7 @@ namespace Ink_Canvas.Windows.SettingsViews if (checkBox != null) { checkBox.IsChecked = isChecked; - + // 尝试多种可能的方法名 var methodNames = new[] { @@ -195,7 +194,7 @@ namespace Ink_Canvas.Windows.SettingsViews checkBoxName + "_Checked", checkBoxName + "_Unchecked" }; - + foreach (var methodName in methodNames) { var method = mainWindow.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); @@ -236,7 +235,7 @@ namespace Ink_Canvas.Windows.SettingsViews { // 调用事件处理方法(它会自动保存设置并触发状态同步) method.Invoke(mainWindow, eventHandlerParams); - + // 如果提供了控件名称,确保状态同步 if (!string.IsNullOrEmpty(controlName)) { @@ -250,7 +249,7 @@ namespace Ink_Canvas.Windows.SettingsViews // 如果没有事件处理方法或调用失败,直接修改设置并保存 action?.Invoke(); MainWindow.SaveSettingsToFile(); - + // 如果提供了控件名称,通知面板同步状态 if (!string.IsNullOrEmpty(controlName)) { @@ -274,7 +273,7 @@ namespace Ink_Canvas.Windows.SettingsViews { action?.Invoke(); MainWindow.SaveSettingsToFile(); - + // 如果提供了控件名称,通知面板同步状态 if (!string.IsNullOrEmpty(controlName)) { @@ -302,14 +301,14 @@ namespace Ink_Canvas.Windows.SettingsViews if (textBox != null) { textBox.Text = text; - + // 触发 TextChanged 事件 var textChangedMethodName = textBoxName + "_TextChanged"; InvokeMainWindowMethod(textChangedMethodName, textBox, new System.Windows.Controls.TextChangedEventArgs( System.Windows.Controls.Primitives.TextBoxBase.TextChangedEvent, System.Windows.Controls.UndoAction.None)); } - + // 通知新设置面板同步状态 NotifySettingsPanelsSyncState(textBoxName); } @@ -336,7 +335,7 @@ namespace Ink_Canvas.Windows.SettingsViews { // 根据控件名称确定需要同步的面板 var panelToSync = GetPanelForControl(controlName); - + if (panelToSync != null) { // 获取对应的面板属性 @@ -347,7 +346,7 @@ namespace Ink_Canvas.Windows.SettingsViews if (panel != null) { // 调用 LoadSettings 方法重新加载设置 - var loadMethod = panel.GetType().GetMethod("LoadSettings", + var loadMethod = panel.GetType().GetMethod("LoadSettings", BindingFlags.Public | BindingFlags.Instance); if (loadMethod != null) { @@ -476,7 +475,7 @@ namespace Ink_Canvas.Windows.SettingsViews { // 获取所有面板属性 var panelProperties = settingsWindow.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Where(p => p.PropertyType.Name.EndsWith("Panel") && + .Where(p => p.PropertyType.Name.EndsWith("Panel") && p.PropertyType.IsSubclassOf(typeof(System.Windows.Controls.UserControl))); foreach (var panelProp in panelProperties) @@ -487,7 +486,7 @@ namespace Ink_Canvas.Windows.SettingsViews if (panel != null) { // 调用 LoadSettings 方法 - var loadMethod = panel.GetType().GetMethod("LoadSettings", + var loadMethod = panel.GetType().GetMethod("LoadSettings", BindingFlags.Public | BindingFlags.Instance); if (loadMethod != null) { @@ -537,12 +536,12 @@ namespace Ink_Canvas.Windows.SettingsViews // 检查是否是主题相关的设置(使用更灵活的匹配) bool isThemeRelated = false; string controlNameLower = controlName.ToLower(); - + foreach (var themeControl in themeRelatedControls) { string themeControlLower = themeControl.ToLower(); // 检查是否包含或匹配 - if (controlNameLower.Contains(themeControlLower) || + if (controlNameLower.Contains(themeControlLower) || themeControlLower.Contains(controlNameLower) || controlNameLower == themeControlLower) { @@ -581,21 +580,21 @@ namespace Ink_Canvas.Windows.SettingsViews if (window.GetType().Name == "SettingsWindow") { // 使用反射调用 ApplyThemeToAllPanels 方法 - var method = window.GetType().GetMethod("ApplyThemeToAllPanels", + var method = window.GetType().GetMethod("ApplyThemeToAllPanels", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (method != null) { method.Invoke(window, null); } - + // 同时调用 ApplyTheme 方法更新窗口本身 - var applyThemeMethod = window.GetType().GetMethod("ApplyTheme", + var applyThemeMethod = window.GetType().GetMethod("ApplyTheme", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (applyThemeMethod != null) { applyThemeMethod.Invoke(window, null); } - + break; // 通常只有一个设置窗口 } } @@ -643,7 +642,7 @@ namespace Ink_Canvas.Windows.SettingsViews for (int i = 0; i < Media.VisualTreeHelper.GetChildrenCount(parent); i++) { var child = Media.VisualTreeHelper.GetChild(parent, i); - + // 为 Border 控件(ToggleSwitch、选项按钮等)启用触摸支持 if (child is Border border) { @@ -651,7 +650,7 @@ namespace Ink_Canvas.Windows.SettingsViews if (border.Tag != null || border.Cursor == Cursors.Hand) { border.IsManipulationEnabled = true; - + // 添加触摸事件支持,将触摸事件转换为鼠标事件 border.TouchDown += (s, e) => { @@ -665,7 +664,7 @@ namespace Ink_Canvas.Windows.SettingsViews border.CaptureTouch(e.TouchDevice); e.Handled = true; }; - + // 添加触摸释放事件 border.TouchUp += (s, e) => { @@ -704,7 +703,7 @@ namespace Ink_Canvas.Windows.SettingsViews { radioButton.IsManipulationEnabled = true; } - + // 递归处理子元素 EnableTouchSupportForControls(child); } diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/PowerPointPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/PowerPointPanel.xaml.cs index 0d411bf8..de955f7c 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/PowerPointPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/PowerPointPanel.xaml.cs @@ -1,8 +1,6 @@ -using Ink_Canvas; using iNKORE.UI.WPF.Helpers; using System; using System.Collections.Generic; -using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; @@ -259,8 +257,8 @@ namespace Ink_Canvas.Windows.SettingsViews private void SetToggleSwitchState(Border toggleSwitch, bool isOn) { if (toggleSwitch == null) return; - toggleSwitch.Background = isOn - ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) + toggleSwitch.Background = isOn + ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) : (ThemeHelper.IsDarkTheme ? ThemeHelper.GetButtonBackgroundBrush() : new SolidColorBrush(Color.FromRgb(225, 225, 225))); var innerBorder = toggleSwitch.Child as Border; if (innerBorder != null) @@ -693,7 +691,7 @@ namespace Ink_Canvas.Windows.SettingsViews break; } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/SearchPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/SearchPanel.xaml.cs index 04b1643f..b564a95f 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/SearchPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/SearchPanel.xaml.cs @@ -1,7 +1,7 @@ +using Microsoft.International.Converters.PinYinConverter; using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; @@ -9,7 +9,6 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; -using Microsoft.International.Converters.PinYinConverter; namespace Ink_Canvas.Windows.SettingsViews { @@ -106,7 +105,7 @@ namespace Ink_Canvas.Windows.SettingsViews { var titleLower = setting.Title.ToLower(); var categoryLower = setting.Category.ToLower(); - + // 精准匹配 if (titleLower.Contains(searchLower) || categoryLower.Contains(searchLower)) { @@ -198,13 +197,13 @@ namespace Ink_Canvas.Windows.SettingsViews { // 将搜索词转换为小写 var searchLower = search.ToLower(); - + // 获取文本的拼音首字母和全拼 var pinyinInitials = GetPinyinInitials(text); var pinyinFull = GetPinyinFull(text); - + // 检查搜索词是否匹配拼音首字母或全拼 - if (pinyinInitials.ToLower().Contains(searchLower) || + if (pinyinInitials.ToLower().Contains(searchLower) || pinyinFull.ToLower().Contains(searchLower)) { return true; @@ -215,7 +214,7 @@ namespace Ink_Canvas.Windows.SettingsViews // 如果拼音转换失败,返回false return false; } - + return false; } @@ -380,7 +379,7 @@ namespace Ink_Canvas.Windows.SettingsViews SearchTextBox.Text = text; PerformSearch(text); } - + /// /// 应用主题 /// @@ -454,7 +453,7 @@ namespace Ink_Canvas.Windows.SettingsViews { try { - Color iconColor = isDarkTheme + Color iconColor = isDarkTheme ? Color.FromRgb(243, 243, 243) // 深色主题使用浅色图标 #F3F3F3 : Color.FromRgb(34, 34, 34); // 浅色主题使用深色图标 #222222 @@ -494,8 +493,8 @@ namespace Ink_Canvas.Windows.SettingsViews { var clonedGeometry = geometryDrawing.Geometry?.Clone(); var clonedBrush = CloneBrush(geometryDrawing.Brush, newColor); - var clonedPen = geometryDrawing.Pen != null - ? ClonePen(geometryDrawing.Pen, newColor) + var clonedPen = geometryDrawing.Pen != null + ? ClonePen(geometryDrawing.Pen, newColor) : null; cloned.Children.Add(new GeometryDrawing(clonedBrush, clonedPen, clonedGeometry)); @@ -525,7 +524,7 @@ namespace Ink_Canvas.Windows.SettingsViews { return new SolidColorBrush(newColor) { Opacity = solidBrush.Opacity }; } - else if (originalColor.A > 0 && originalColor != Colors.Transparent && + else if (originalColor.A > 0 && originalColor != Colors.Transparent && originalColor.R < 50 && originalColor.G < 50 && originalColor.B < 50) // 深色 { return new SolidColorBrush(newColor) { Opacity = solidBrush.Opacity }; diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/SecurityPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/SecurityPanel.xaml.cs index 9fa3b7c1..d3a9576f 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/SecurityPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/SecurityPanel.xaml.cs @@ -1,5 +1,4 @@ using Ink_Canvas.Helpers; -using iNKORE.UI.WPF.Helpers; using System; using System.Windows; using System.Windows.Controls; diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/SettingsPanelBase.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/SettingsPanelBase.cs index fe19b60a..25e3ffe5 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/SettingsPanelBase.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/SettingsPanelBase.cs @@ -1,4 +1,3 @@ -using Ink_Canvas; using iNKORE.UI.WPF.Helpers; using System; using System.Windows; @@ -45,7 +44,7 @@ namespace Ink_Canvas.Windows.SettingsViews { System.Diagnostics.Debug.WriteLine($"SettingsPanelBase 应用主题时出错: {ex.Message}"); } - LoadSettings(); + LoadSettings(); _isLoaded = true; } @@ -78,7 +77,7 @@ namespace Ink_Canvas.Windows.SettingsViews for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { var child = VisualTreeHelper.GetChild(parent, i); - + // 为 Border 控件(ToggleSwitch、选项按钮等)启用触摸支持 if (child is Border border) { @@ -86,7 +85,7 @@ namespace Ink_Canvas.Windows.SettingsViews if (border.Tag != null || border.Cursor == Cursors.Hand) { border.IsManipulationEnabled = true; - + // 添加触摸事件支持,将触摸事件转换为鼠标事件 border.TouchDown += Border_TouchDown; border.PreviewTouchDown += Border_PreviewTouchDown; @@ -112,7 +111,7 @@ namespace Ink_Canvas.Windows.SettingsViews { textBox.IsManipulationEnabled = true; } - + // 递归处理子元素 EnableTouchSupportForControls(child); } @@ -128,17 +127,17 @@ namespace Ink_Canvas.Windows.SettingsViews // 获取触摸点位置 var touchPoint = e.GetTouchPoint(border); - + // 创建模拟的鼠标事件 var mouseButtonEventArgs = new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Left) { RoutedEvent = UIElement.MouseLeftButtonDownEvent, Source = border }; - + // 触发鼠标按下事件 border.RaiseEvent(mouseButtonEventArgs); - + // 捕获触摸设备 border.CaptureTouch(e.TouchDevice); e.Handled = true; @@ -154,17 +153,17 @@ namespace Ink_Canvas.Windows.SettingsViews // 获取触摸点位置 var touchPoint = e.GetTouchPoint(border); - + // 创建模拟的鼠标事件 var mouseButtonEventArgs = new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Left) { RoutedEvent = UIElement.PreviewMouseLeftButtonDownEvent, Source = border }; - + // 触发预览鼠标按下事件 border.RaiseEvent(mouseButtonEventArgs); - + e.Handled = true; } @@ -187,8 +186,8 @@ namespace Ink_Canvas.Windows.SettingsViews protected void SetToggleSwitchState(Border toggleSwitch, bool isOn) { if (toggleSwitch == null) return; - toggleSwitch.Background = isOn - ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) + toggleSwitch.Background = isOn + ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) : (ThemeHelper.IsDarkTheme ? ThemeHelper.GetButtonBackgroundBrush() : new SolidColorBrush(Color.FromRgb(225, 225, 225))); var innerBorder = toggleSwitch.Child as Border; if (innerBorder != null) diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/ShortcutsPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/ShortcutsPanel.xaml.cs index bd20df56..730ebc36 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/ShortcutsPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/ShortcutsPanel.xaml.cs @@ -29,7 +29,7 @@ namespace Ink_Canvas.Windows.SettingsViews IsTopBarNeedNoShadowEffect?.Invoke(this, new RoutedEventArgs()); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/SnapshotPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/SnapshotPanel.xaml.cs index a745c0c9..d281660c 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/SnapshotPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/SnapshotPanel.xaml.cs @@ -1,4 +1,3 @@ -using Ink_Canvas; using iNKORE.UI.WPF.Helpers; using System; using System.IO; @@ -158,8 +157,8 @@ namespace Ink_Canvas.Windows.SettingsViews private void SetToggleSwitchState(Border toggleSwitch, bool isOn) { if (toggleSwitch == null) return; - toggleSwitch.Background = isOn - ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) + toggleSwitch.Background = isOn + ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) : (ThemeHelper.IsDarkTheme ? ThemeHelper.GetButtonBackgroundBrush() : new SolidColorBrush(Color.FromRgb(225, 225, 225))); var innerBorder = toggleSwitch.Child as Border; if (innerBorder != null) @@ -217,7 +216,7 @@ namespace Ink_Canvas.Windows.SettingsViews bool currentState = GetCurrentSettingValue(tag); bool newState = !currentState; - + SetToggleSwitchState(border, newState); switch (tag) @@ -391,7 +390,7 @@ namespace Ink_Canvas.Windows.SettingsViews } } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/StartupPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/StartupPanel.xaml.cs index 72310ac5..8dd43956 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/StartupPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/StartupPanel.xaml.cs @@ -1,7 +1,5 @@ -using Ink_Canvas; using iNKORE.UI.WPF.Helpers; using System; -using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; @@ -283,7 +281,7 @@ namespace Ink_Canvas.Windows.SettingsViews } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/StoragePanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/StoragePanel.xaml.cs index f4adcd5a..1f1aafd6 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/StoragePanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/StoragePanel.xaml.cs @@ -29,7 +29,7 @@ namespace Ink_Canvas.Windows.SettingsViews IsTopBarNeedNoShadowEffect?.Invoke(this, new RoutedEventArgs()); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/ThemeHelper.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/ThemeHelper.cs index 00bf5db6..9d973bf4 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/ThemeHelper.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/ThemeHelper.cs @@ -1,5 +1,4 @@ using System.Windows.Media; -using Ink_Canvas; namespace Ink_Canvas.Windows.SettingsViews { @@ -184,7 +183,7 @@ namespace Ink_Canvas.Windows.SettingsViews else if (color.R == 225 && color.G == 225 && color.B == 225) // #e1e1e1 - 按钮背景/分隔线 { // 检查是否是按钮(有内边距或特定尺寸) - if (border.Padding.Left > 0 || border.Padding.Top > 0 || + if (border.Padding.Left > 0 || border.Padding.Top > 0 || (border.Width > 0 && border.Height > 0 && border.Width < 200 && border.Height < 100)) { border.Background = GetButtonBackgroundBrush(); @@ -198,12 +197,12 @@ namespace Ink_Canvas.Windows.SettingsViews else if (color.R == 255 && color.G == 255 && color.B == 255) // White - 白色背景 { // 检查是否是搜索结果项(有圆角和内边距) - if (border.CornerRadius.TopLeft == 6 && border.CornerRadius.TopRight == 6 && + if (border.CornerRadius.TopLeft == 6 && border.CornerRadius.TopRight == 6 && border.CornerRadius.BottomLeft == 6 && border.CornerRadius.BottomRight == 6 && border.Padding.Left > 0 && border.Padding.Top > 0) { // 搜索结果项背景 - border.Background = IsDarkTheme + border.Background = IsDarkTheme ? new SolidColorBrush(Color.FromRgb(43, 43, 43)) // 深色主题搜索结果项背景 : new SolidColorBrush(Colors.White); } @@ -222,7 +221,7 @@ namespace Ink_Canvas.Windows.SettingsViews border.Background = GetBackgroundPrimaryBrush(); } } - + var borderBrush = border.BorderBrush as SolidColorBrush; if (borderBrush != null) { @@ -332,7 +331,7 @@ namespace Ink_Canvas.Windows.SettingsViews if (color.R == 37 && color.G == 99 && color.B == 235) // #2563eb - 蓝色按钮(保持原色) { // 蓝色按钮保持原色,但更新文字颜色 - if (button.Foreground is SolidColorBrush fgBrush && + if (button.Foreground is SolidColorBrush fgBrush && fgBrush.Color.R == 255 && fgBrush.Color.G == 255 && fgBrush.Color.B == 255) { button.Foreground = new SolidColorBrush(Colors.White); // 保持白色文字 @@ -371,10 +370,10 @@ namespace Ink_Canvas.Windows.SettingsViews { if (drawingImage.Drawing is DrawingGroup drawingGroup) { - Color iconColor = IsDarkTheme + Color iconColor = IsDarkTheme ? Color.FromRgb(243, 243, 243) // 深色主题使用浅色图标 #F3F3F3 : Color.FromRgb(34, 34, 34); // 浅色主题使用深色图标 #222222 - + // 检查图标是否使用了深色(需要更新的颜色) bool needsUpdate = false; foreach (var drawing in drawingGroup.Children) @@ -401,7 +400,7 @@ namespace Ink_Canvas.Windows.SettingsViews } } } - + if (needsUpdate) { // 克隆并更新图标颜色 @@ -430,8 +429,8 @@ namespace Ink_Canvas.Windows.SettingsViews { var clonedGeometry = geometryDrawing.Geometry?.Clone(); var clonedBrush = CloneBrushForTheme(geometryDrawing.Brush, newColor); - var clonedPen = geometryDrawing.Pen != null - ? ClonePenForTheme(geometryDrawing.Pen, newColor) + var clonedPen = geometryDrawing.Pen != null + ? ClonePenForTheme(geometryDrawing.Pen, newColor) : null; cloned.Children.Add(new GeometryDrawing(clonedBrush, clonedPen, clonedGeometry)); @@ -461,7 +460,7 @@ namespace Ink_Canvas.Windows.SettingsViews { return new SolidColorBrush(newColor) { Opacity = solidBrush.Opacity }; } - else if (originalColor.A > 0 && originalColor != Colors.Transparent && + else if (originalColor.A > 0 && originalColor != Colors.Transparent && originalColor.R < 50 && originalColor.G < 50 && originalColor.B < 50) // 深色 { return new SolidColorBrush(newColor) { Opacity = solidBrush.Opacity }; diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/ThemePanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/ThemePanel.xaml.cs index 31145759..10fc0f34 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/ThemePanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/ThemePanel.xaml.cs @@ -1,13 +1,10 @@ -using Ink_Canvas; +using Hardcodet.Wpf.TaskbarNotification; using iNKORE.UI.WPF.Helpers; using System; using System.Collections.Generic; -using System.Linq; -using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Media; -using Hardcodet.Wpf.TaskbarNotification; namespace Ink_Canvas.Windows.SettingsViews { @@ -104,7 +101,7 @@ namespace Ink_Canvas.Windows.SettingsViews { // 更新自定义图标列表(如果需要) // UpdateCustomIconsInComboBox(); - + int selectedIndex = Math.Min(appearance.FloatingBarImg, ComboBoxFloatingBarImg.Items.Count - 1); ComboBoxFloatingBarImg.SelectedIndex = selectedIndex; } @@ -228,8 +225,8 @@ namespace Ink_Canvas.Windows.SettingsViews private void SetToggleSwitchState(Border toggleSwitch, bool isOn) { if (toggleSwitch == null) return; - toggleSwitch.Background = isOn - ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) + toggleSwitch.Background = isOn + ? new SolidColorBrush(Color.FromRgb(53, 132, 228)) : (ThemeHelper.IsDarkTheme ? ThemeHelper.GetButtonBackgroundBrush() : new SolidColorBrush(Color.FromRgb(225, 225, 225))); var innerBorder = toggleSwitch.Child as Border; if (innerBorder != null) @@ -624,7 +621,7 @@ namespace Ink_Canvas.Windows.SettingsViews themeIndex = 2; break; } - + if (comboBox.Items.Count > themeIndex) { var selectedItem = comboBox.Items[themeIndex]; @@ -638,7 +635,7 @@ namespace Ink_Canvas.Windows.SettingsViews appearance.Theme = themeIndex; }, "ComboBoxTheme_SelectionChanged", "ComboBoxTheme"); MainWindowSettingsHelper.NotifyThemeUpdateIfNeeded("ComboBoxTheme"); - + // 触发主题变化事件,通知设置窗口更新主题 ThemeChanged?.Invoke(this, new RoutedEventArgs()); } @@ -667,7 +664,7 @@ namespace Ink_Canvas.Windows.SettingsViews appearance.Theme = themeIndex; }, "ComboBoxTheme_SelectionChanged", "ComboBoxTheme"); MainWindowSettingsHelper.NotifyThemeUpdateIfNeeded("ComboBoxTheme"); - + // 触发主题变化事件,通知设置窗口更新主题 ThemeChanged?.Invoke(this, new RoutedEventArgs()); } @@ -833,7 +830,7 @@ namespace Ink_Canvas.Windows.SettingsViews break; } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/TimerPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/TimerPanel.xaml.cs index 1d0ee8c6..cf33f551 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/TimerPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/TimerPanel.xaml.cs @@ -29,7 +29,7 @@ namespace Ink_Canvas.Windows.SettingsViews IsTopBarNeedNoShadowEffect?.Invoke(this, new RoutedEventArgs()); } } - + /// /// 应用主题 /// diff --git a/Ink Canvas/Windows/SettingsViews/SettingsViews/UpdateCenterPanel.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsViews/UpdateCenterPanel.xaml.cs index ba7d347c..8d7828ef 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsViews/UpdateCenterPanel.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsViews/UpdateCenterPanel.xaml.cs @@ -1,6 +1,6 @@ +using Ink_Canvas.Helpers; using iNKORE.UI.WPF.Helpers; using iNKORE.UI.WPF.Modern.Controls; -using Ink_Canvas.Helpers; using System; using System.Collections.Generic; using System.Linq; @@ -9,8 +9,8 @@ using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; -using MessageBox = iNKORE.UI.WPF.Modern.Controls.MessageBox; using static Ink_Canvas.Helpers.AutoUpdateHelper; +using MessageBox = iNKORE.UI.WPF.Modern.Controls.MessageBox; namespace Ink_Canvas.Windows.SettingsViews { @@ -70,7 +70,7 @@ namespace Ink_Canvas.Windows.SettingsViews if (AutoUpdateTimePeriodBlock != null) { - AutoUpdateTimePeriodBlock.Visibility = + AutoUpdateTimePeriodBlock.Visibility = (MainWindow.Settings.Startup.IsAutoUpdateWithSilence && MainWindow.Settings.Startup.IsAutoUpdate) ? Visibility.Visible : Visibility.Collapsed; } @@ -127,7 +127,7 @@ namespace Ink_Canvas.Windows.SettingsViews { var now = DateTime.Now; var timeDiff = now - lastCheckTime; - + if (timeDiff.TotalDays < 1 && lastCheckTime.Date == now.Date) { LastCheckTimeText.Text = $"上次检查时间: 今天, {lastCheckTime:HH:mm}"; @@ -241,7 +241,7 @@ namespace Ink_Canvas.Windows.SettingsViews } var groups = _availableLineGroup != null ? new List { _availableLineGroup } : AutoUpdateHelper.ChannelLineGroups[updateChannel]; - + bool downloadSuccess = await AutoUpdateHelper.DownloadSetupFileWithFallback(_availableVersion, groups, (percent, text) => { Dispatcher.BeginInvoke(new Action(() => @@ -298,7 +298,7 @@ namespace Ink_Canvas.Windows.SettingsViews } var groups = _availableLineGroup != null ? new List { _availableLineGroup } : AutoUpdateHelper.ChannelLineGroups[updateChannel]; - + bool downloadSuccess = await AutoUpdateHelper.DownloadSetupFileWithFallback(_availableVersion, groups, (percent, text) => { Dispatcher.BeginInvoke(new Action(() => @@ -404,7 +404,7 @@ namespace Ink_Canvas.Windows.SettingsViews } var (remoteVersion, lineGroup, releaseNotes) = await AutoUpdateHelper.CheckForUpdates(updateChannel, manualCheck, false); - + if (manualCheck) { var mainWindow = Application.Current.MainWindow as MainWindow; @@ -417,20 +417,20 @@ namespace Ink_Canvas.Windows.SettingsViews } } } - + Dispatcher.BeginInvoke(new Action(() => { StopLoadingAnimation(); - + if (!string.IsNullOrEmpty(remoteVersion)) { var localVersion = Assembly.GetExecutingAssembly().GetName().Version; var localVersionStr = localVersion.ToString(); var remoteVersionStr = remoteVersion.TrimStart('v', 'V'); - + Version local = new Version(localVersionStr); Version remote = new Version(remoteVersionStr); - + if (remote > local) { UpdateStatusText.Text = "有可用更新"; @@ -463,12 +463,12 @@ namespace Ink_Canvas.Windows.SettingsViews { LoadUpdateLogAsFallback(updateChannel); } - + if (manualCheck) { SaveLastCheckTime(); } - + CheckUpdateButton.IsEnabled = true; })); } @@ -512,7 +512,7 @@ namespace Ink_Canvas.Windows.SettingsViews try { var (remoteVersion, lineGroup, releaseNotes) = await AutoUpdateHelper.CheckForUpdates(channel, false, false); - + if (!string.IsNullOrEmpty(releaseNotes)) { UpdateLogViewer.Markdown = releaseNotes; @@ -543,12 +543,12 @@ namespace Ink_Canvas.Windows.SettingsViews } _historyVersions = await AutoUpdateHelper.GetAllGithubReleases(updateChannel); - + if (_historyVersions.Count > 0) { var markdown = new System.Text.StringBuilder(); markdown.AppendLine("# 历史版本列表\n"); - + foreach (var (version, downloadUrl, releaseNotes) in _historyVersions) { markdown.AppendLine($"## {version}\n"); @@ -559,7 +559,7 @@ namespace Ink_Canvas.Windows.SettingsViews } markdown.AppendLine("\n---\n"); } - + HistoryLogViewer.Markdown = markdown.ToString(); foreach (var versionInfo in _historyVersions) @@ -591,7 +591,7 @@ namespace Ink_Canvas.Windows.SettingsViews var version = versionInfo.Item1; var downloadUrl = versionInfo.Item2; var releaseNotes = versionInfo.Item3; - + if (!string.IsNullOrEmpty(releaseNotes)) { HistoryLogViewer.Markdown = $"# {version}\n\n{releaseNotes}"; @@ -776,7 +776,7 @@ namespace Ink_Canvas.Windows.SettingsViews { MainWindow.Settings.Startup.UpdateChannel = UpdateChannel.Release; }, "UpdateChannelSelector"); - MainWindowSettingsHelper.InvokeMainWindowMethod("UpdateChannelSelector_Checked", + MainWindowSettingsHelper.InvokeMainWindowMethod("UpdateChannelSelector_Checked", new System.Windows.Controls.RadioButton { Tag = "Release" }, e); UpdateUpdateChannelButtons(UpdateChannel.Release); LoadHistoryVersions(); @@ -788,7 +788,7 @@ namespace Ink_Canvas.Windows.SettingsViews { MainWindow.Settings.Startup.UpdateChannel = UpdateChannel.Preview; }, "UpdateChannelSelector"); - MainWindowSettingsHelper.InvokeMainWindowMethod("UpdateChannelSelector_Checked", + MainWindowSettingsHelper.InvokeMainWindowMethod("UpdateChannelSelector_Checked", new System.Windows.Controls.RadioButton { Tag = "Preview" }, e); UpdateUpdateChannelButtons(UpdateChannel.Preview); LoadHistoryVersions(); @@ -800,7 +800,7 @@ namespace Ink_Canvas.Windows.SettingsViews { MainWindow.Settings.Startup.UpdateChannel = UpdateChannel.Beta; }, "UpdateChannelSelector"); - MainWindowSettingsHelper.InvokeMainWindowMethod("UpdateChannelSelector_Checked", + MainWindowSettingsHelper.InvokeMainWindowMethod("UpdateChannelSelector_Checked", new System.Windows.Controls.RadioButton { Tag = "Beta" }, e); UpdateUpdateChannelButtons(UpdateChannel.Beta); LoadHistoryVersions(); @@ -816,7 +816,7 @@ namespace Ink_Canvas.Windows.SettingsViews bool isDarkTheme = ThemeHelper.IsDarkTheme; var selectedBrush = isDarkTheme ? new SolidColorBrush(Color.FromRgb(25, 25, 25)) : new SolidColorBrush(Color.FromRgb(225, 225, 225)); var unselectedBrush = new SolidColorBrush(Colors.Transparent); - + if (UpdateChannelReleaseBorder != null) { bool isSelected = selectedChannel == UpdateChannel.Release; @@ -828,7 +828,7 @@ namespace Ink_Canvas.Windows.SettingsViews textBlock.Foreground = ThemeHelper.GetTextPrimaryBrush(); } } - + if (UpdateChannelPreviewBorder != null) { bool isSelected = selectedChannel == UpdateChannel.Preview; @@ -840,7 +840,7 @@ namespace Ink_Canvas.Windows.SettingsViews textBlock.Foreground = ThemeHelper.GetTextPrimaryBrush(); } } - + if (UpdateChannelBetaBorder != null) { bool isSelected = selectedChannel == UpdateChannel.Beta; @@ -881,7 +881,7 @@ namespace Ink_Canvas.Windows.SettingsViews AutoUpdateTimePeriodSeparator.Visibility = newState ? Visibility.Visible : Visibility.Collapsed; if (AutoUpdateTimePeriodBlock != null) { - AutoUpdateTimePeriodBlock.Visibility = + AutoUpdateTimePeriodBlock.Visibility = (MainWindow.Settings.Startup.IsAutoUpdateWithSilence && MainWindow.Settings.Startup.IsAutoUpdate) ? Visibility.Visible : Visibility.Collapsed; } @@ -971,20 +971,20 @@ namespace Ink_Canvas.Windows.SettingsViews try { ThemeHelper.ApplyThemeToControl(this); - + if (UpdateAvailableBorder != null) { UpdateAvailableBorder.Background = ThemeHelper.GetBackgroundPrimaryBrush(); UpdateAvailableBorder.BorderBrush = ThemeHelper.GetBorderPrimaryBrush(); } - + if (CheckUpdateButton != null) { CheckUpdateButton.Background = ThemeHelper.GetButtonBackgroundBrush(); CheckUpdateButton.Foreground = ThemeHelper.GetTextPrimaryBrush(); CheckUpdateButton.BorderBrush = ThemeHelper.GetBorderPrimaryBrush(); } - + if (UpdateNowButton != null) { UpdateNowButton.Background = new SolidColorBrush(Color.FromRgb(37, 99, 235)); diff --git a/Ink Canvas/Windows/SettingsViews/SettingsWindow.xaml.cs b/Ink Canvas/Windows/SettingsViews/SettingsWindow.xaml.cs index fa318c7b..b4e18967 100644 --- a/Ink Canvas/Windows/SettingsViews/SettingsWindow.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/SettingsWindow.xaml.cs @@ -1,5 +1,5 @@ -using iNKORE.UI.WPF.Helpers; using Ink_Canvas.Windows.SettingsViews; +using iNKORE.UI.WPF.Helpers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -26,14 +26,14 @@ namespace Ink_Canvas.Windows public SettingsWindow() { InitializeComponent(); - + // 获取 MainWindow 实例 _mainWindow = Application.Current.MainWindow as MainWindow; - + // 初始化搜索面板事件 SearchPanelControl.NavigateToItem += SearchPanel_NavigateToItem; SearchPanelControl.CloseSearch += SearchPanel_CloseSearch; - + // 订阅菜单关闭事件,确保状态同步 if (MenuButtonContextMenu != null) { @@ -272,9 +272,9 @@ namespace Ink_Canvas.Windows PowerPointPanel.IsTopBarNeedNoShadowEffect += (o, s) => DropShadowEffectTopBar.Opacity = 0; ThemePanel.IsTopBarNeedShadowEffect += (o, s) => DropShadowEffectTopBar.Opacity = 0.25; ThemePanel.IsTopBarNeedNoShadowEffect += (o, s) => DropShadowEffectTopBar.Opacity = 0; - + // 监听主题变化 - ThemePanel.ThemeChanged += (o, s) => + ThemePanel.ThemeChanged += (o, s) => { ApplyTheme(); ApplyThemeToAllPanels(); @@ -295,16 +295,16 @@ namespace Ink_Canvas.Windows UpdateCenterPanel.IsTopBarNeedNoShadowEffect += (o, s) => DropShadowEffectTopBar.Opacity = 0; _selectedSidebarItemName = "StartupItem"; - + // 初始化侧边栏项目的主题状态 - bool isDarkTheme = MainWindow.Settings?.Appearance != null && + bool isDarkTheme = MainWindow.Settings?.Appearance != null && (MainWindow.Settings.Appearance.Theme == 1 || (MainWindow.Settings.Appearance.Theme == 2 && !IsSystemThemeLight())); foreach (var item in SidebarItems) { item.IsDarkTheme = isDarkTheme; } - + UpdateSidebarItemsSelection(); // 为自定义滑块控件添加触摸支持 @@ -312,13 +312,13 @@ namespace Ink_Canvas.Windows // 先应用主题,确保标题栏等元素正确显示 ApplyTheme(); - + // 加载所有面板的设置 LoadAllPanelsSettings(); - + // 通知所有面板应用主题 ApplyThemeToAllPanels(); - + // 延迟再次应用主题,确保所有元素都正确应用主题(特别是标题栏) Dispatcher.BeginInvoke(new Action(() => { @@ -326,7 +326,7 @@ namespace Ink_Canvas.Windows ApplyThemeToAllPanels(); }), System.Windows.Threading.DispatcherPriority.Loaded); } - + /// /// 通知所有已注册的设置面板应用当前主题配置,使各面板更新其视觉样式以匹配窗口主题。 /// @@ -337,10 +337,10 @@ namespace Ink_Canvas.Windows { try { - bool isDarkTheme = MainWindow.Settings?.Appearance != null && + bool isDarkTheme = MainWindow.Settings?.Appearance != null && (MainWindow.Settings.Appearance.Theme == 1 || (MainWindow.Settings.Appearance.Theme == 2 && !IsSystemThemeLight())); - + // 使用反射调用所有面板的 ApplyTheme 方法(如果存在) var panels = new UserControl[] { @@ -349,12 +349,12 @@ namespace Ink_Canvas.Windows AutomationPanel, LuckyRandomPanel, AdvancedPanel, SnapshotPanel, SettingsAboutPanel, AppearancePanel, SearchPanelControl }; - + foreach (var panel in panels) { if (panel != null) { - var method = panel.GetType().GetMethod("ApplyTheme", + var method = panel.GetType().GetMethod("ApplyTheme", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (method != null) { @@ -443,14 +443,14 @@ namespace Ink_Canvas.Windows { topBarBackgroundBorderFallback.Background = ThemeHelper.GetBackgroundPrimaryBrush(); // Windows 系统主背景 } - + // 更新侧边栏项目文本颜色 foreach (var item in SidebarItems) { // 通过反射或直接访问来更新文本颜色 // 这里需要在 XAML 中绑定或通过其他方式更新 } - + // 更新滚动条样式 - 参考 Windows 系统设置 var scrollBarTrack = this.FindDescendantByName("ScrollBarBorderTrackBackground") as Border; if (scrollBarTrack != null) @@ -458,14 +458,14 @@ namespace Ink_Canvas.Windows scrollBarTrack.Background = ThemeHelper.GetScrollBarTrackBrush(); // Windows 系统滚动条轨道 scrollBarTrack.Opacity = 0.3; } - + // 更新侧边栏项目主题 foreach (var item in SidebarItems) { item.IsDarkTheme = true; } CollectionViewSource.GetDefaultView(SidebarItems).Refresh(); - + // 更新图标颜色 UpdateIconColors(true); } @@ -524,7 +524,7 @@ namespace Ink_Canvas.Windows { topBarBackgroundBorderFallback.Background = new SolidColorBrush(Color.FromRgb(250, 250, 250)); } - + // 更新滚动条样式 var scrollBarTrack = this.FindDescendantByName("ScrollBarBorderTrackBackground") as Border; if (scrollBarTrack != null) @@ -532,14 +532,14 @@ namespace Ink_Canvas.Windows scrollBarTrack.Background = ThemeHelper.GetScrollBarTrackBrush(); // Windows 系统滚动条轨道 scrollBarTrack.Opacity = 0; } - + // 更新侧边栏项目主题 foreach (var item in SidebarItems) { item.IsDarkTheme = false; } CollectionViewSource.GetDefaultView(SidebarItems).Refresh(); - + // 更新图标颜色 UpdateIconColors(false); } @@ -558,14 +558,14 @@ namespace Ink_Canvas.Windows try { // 根据主题选择颜色 - Color iconColor = isDarkTheme + Color iconColor = isDarkTheme ? Color.FromRgb(243, 243, 243) // 深色主题使用浅色图标 #F3F3F3 : Color.FromRgb(34, 34, 34); // 浅色主题使用深色图标 #222222 // 更新每个侧边栏项目的图标 foreach (var item in SidebarItems) { - if (item.IconSource is DrawingImage drawingImage && + if (item.IconSource is DrawingImage drawingImage && drawingImage.Drawing is DrawingGroup drawingGroup) { // 克隆并更新图标 @@ -573,7 +573,7 @@ namespace Ink_Canvas.Windows item.IconSource = new DrawingImage { Drawing = clonedDrawing }; } } - + CollectionViewSource.GetDefaultView(SidebarItems).Refresh(); } catch (Exception ex) @@ -598,8 +598,8 @@ namespace Ink_Canvas.Windows { var clonedGeometry = geometryDrawing.Geometry?.Clone(); var clonedBrush = CloneBrush(geometryDrawing.Brush, newColor); - var clonedPen = geometryDrawing.Pen != null - ? ClonePen(geometryDrawing.Pen, newColor) + var clonedPen = geometryDrawing.Pen != null + ? ClonePen(geometryDrawing.Pen, newColor) : null; cloned.Children.Add(new GeometryDrawing(clonedBrush, clonedPen, clonedGeometry)); @@ -631,7 +631,7 @@ namespace Ink_Canvas.Windows { return new SolidColorBrush(newColor) { Opacity = solidBrush.Opacity }; } - else if (originalColor.A > 0 && originalColor != Colors.Transparent && + else if (originalColor.A > 0 && originalColor != Colors.Transparent && originalColor.R < 50 && originalColor.G < 50 && originalColor.B < 50) // 深色 { return new SolidColorBrush(newColor) { Opacity = solidBrush.Opacity }; @@ -664,7 +664,7 @@ namespace Ink_Canvas.Windows { try { - Color iconColor = isDarkTheme + Color iconColor = isDarkTheme ? Color.FromRgb(243, 243, 243) // 深色主题使用浅色图标 #F3F3F3 : Color.FromRgb(34, 34, 34); // 浅色主题使用深色图标 #222222 @@ -700,7 +700,7 @@ namespace Ink_Canvas.Windows { try { - Color iconColor = isDarkTheme + Color iconColor = isDarkTheme ? Color.FromRgb(243, 243, 243) // 深色主题使用浅色图标 #F3F3F3 : Color.FromRgb(34, 34, 34); // 浅色主题使用深色图标 #222222 @@ -813,7 +813,7 @@ namespace Ink_Canvas.Windows { loadSettingsMethod.Invoke(panel, null); } - + // 调用 EnableTouchSupport 确保触摸支持已启用 var enableTouchSupportMethod = panel.GetType().GetMethod("EnableTouchSupport", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); @@ -826,7 +826,7 @@ namespace Ink_Canvas.Windows // 如果面板没有 EnableTouchSupport 方法,直接使用 MainWindowSettingsHelper MainWindowSettingsHelper.EnableTouchSupportForControls(panel); } - + // 调用 ApplyTheme 确保主题已应用 var applyThemeMethod = panel.GetType().GetMethod("ApplyTheme", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); @@ -841,7 +841,7 @@ namespace Ink_Canvas.Windows } } } - + // 再次应用主题到所有面板,确保主题完全加载 Dispatcher.BeginInvoke(new Action(() => { @@ -876,7 +876,7 @@ namespace Ink_Canvas.Windows public ImageSource IconSource { get; set; } private bool _selected = false; private bool _isDarkTheme = false; - + public bool Selected { get => _selected; @@ -886,7 +886,7 @@ namespace Ink_Canvas.Windows OnPropertyChanged(nameof(_siBackground)); } } - + public bool IsDarkTheme { get => _isDarkTheme; @@ -898,7 +898,7 @@ namespace Ink_Canvas.Windows OnPropertyChanged(nameof(_spStroke)); } } - + public Visibility _spVisibility { get => Type == SidebarItemType.Separator ? Visibility.Visible : Visibility.Collapsed; @@ -921,21 +921,21 @@ namespace Ink_Canvas.Windows return new SolidColorBrush(Colors.Transparent); } } - + public SolidColorBrush _siForeground { get => _isDarkTheme ? ThemeHelper.GetTextPrimaryBrush() // Windows 系统主文字颜色 #F3F3F3 : new SolidColorBrush(Color.FromRgb(0, 0, 0)); } - + public SolidColorBrush _spStroke { get => _isDarkTheme ? ThemeHelper.GetSeparatorBrush() // Windows 系统分隔线 #3E3E3E : new SolidColorBrush(Color.FromRgb(237, 237, 237)); } - + public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { @@ -972,9 +972,9 @@ namespace Ink_Canvas.Windows } } CollectionViewSource.GetDefaultView(SidebarItems).Refresh(); - + // 确保主题状态同步 - bool isDarkTheme = MainWindow.Settings?.Appearance != null && + bool isDarkTheme = MainWindow.Settings?.Appearance != null && (MainWindow.Settings.Appearance.Theme == 1 || (MainWindow.Settings.Appearance.Theme == 2 && !IsSystemThemeLight())); foreach (var si in SidebarItems) @@ -1002,7 +1002,7 @@ namespace Ink_Canvas.Windows { "UpdateCenterItem", UpdateCenterPanel }, { "AppearanceItem", AppearancePanel } }; - + // 设置面板可见性并应用主题 if (AboutPane != null) AboutPane.Visibility = _selectedSidebarItemName == "AboutItem" ? Visibility.Visible : Visibility.Collapsed; if (CanvasAndInkPane != null) CanvasAndInkPane.Visibility = _selectedSidebarItemName == "CanvasAndInkItem" ? Visibility.Visible : Visibility.Collapsed; @@ -1019,7 +1019,7 @@ namespace Ink_Canvas.Windows if (SnapshotPane != null) SnapshotPane.Visibility = _selectedSidebarItemName == "SnapshotItem" ? Visibility.Visible : Visibility.Collapsed; if (SecurityPane != null) SecurityPane.Visibility = _selectedSidebarItemName == "SecurityItem" ? Visibility.Visible : Visibility.Collapsed; if (UpdateCenterPane != null) UpdateCenterPane.Visibility = _selectedSidebarItemName == "UpdateCenterItem" ? Visibility.Visible : Visibility.Collapsed; - + // 为新显示的面板应用主题(延迟执行,确保面板已完全显示) if (panelMappings.ContainsKey(_selectedSidebarItemName)) { @@ -1176,7 +1176,7 @@ namespace Ink_Canvas.Windows { // 隐藏搜索界面 SearchPane.Visibility = Visibility.Collapsed; - + // 导航到对应的设置项 NavigateToSidebarItem(itemName); } @@ -1213,10 +1213,10 @@ namespace Ink_Canvas.Windows { MenuButtonContextMenu.PlacementTarget = MenuButtonBorder; MenuButtonContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom; - + // 如果菜单已打开,则关闭;如果已关闭,则打开 bool isCurrentlyOpen = MenuButtonContextMenu.IsOpen; - + if (isCurrentlyOpen) { // 如果菜单已打开,直接关闭 @@ -1227,7 +1227,7 @@ namespace Ink_Canvas.Windows // 如果菜单未打开,打开菜单 MenuButtonContextMenu.IsOpen = true; } - + // 标记事件已处理,防止菜单拦截点击 e.Handled = true; } @@ -1237,7 +1237,7 @@ namespace Ink_Canvas.Windows { // 关闭设置窗口 Close(); - + // 调用主窗口的退出方法 if (_mainWindow != null) { @@ -1249,7 +1249,7 @@ namespace Ink_Canvas.Windows { // 关闭设置窗口 Close(); - + // 调用主窗口的重启方法 if (_mainWindow != null) { diff --git a/Ink Canvas/Windows/TimerControl.xaml.cs b/Ink Canvas/Windows/TimerControl.xaml.cs index 90fb7594..5452e1c5 100644 --- a/Ink Canvas/Windows/TimerControl.xaml.cs +++ b/Ink Canvas/Windows/TimerControl.xaml.cs @@ -65,29 +65,29 @@ namespace Ink_Canvas.Windows { var dpiScaleX = source.CompositionTarget.TransformToDevice.M11; var dpiScaleY = source.CompositionTarget.TransformToDevice.M22; - + // 如果DPI缩放因子大于1.25,则适当缩小最大尺寸 // 这样可以确保在高DPI屏幕上,计时器窗口的物理像素大小不会过大 if (dpiScaleX > 1.25 || dpiScaleY > 1.25) { // 使用较小的缩放因子来限制最大尺寸 double scaleFactor = Math.Min(dpiScaleX, dpiScaleY); - + if (MainViewController != null) { // 计算目标物理像素大小(约1350x750物理像素) // 然后转换为逻辑像素 double targetPhysicalWidth = 1350; double targetPhysicalHeight = 750; - + // 转换为逻辑像素 double maxWidth = targetPhysicalWidth / scaleFactor; double maxHeight = targetPhysicalHeight / scaleFactor; - + // 确保不会小于原始尺寸的70% maxWidth = Math.Max(maxWidth, 900 * 0.7); maxHeight = Math.Max(maxHeight, 500 * 0.7); - + MainViewController.MaxWidth = maxWidth; MainViewController.MaxHeight = maxHeight; }