macad解析macad-windows篇

2024-02-19 21:44
文章标签 windows 解析 macad

本文主要是介绍macad解析macad-windows篇,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.

using System.Diagnostics;
using System.Reflection;
using Macad.Presentation;namespace Macad.Window
{/// <summary>/// Interaction logic for AboutDialog.xaml/// </summary>public partial class AboutDialog : Dialog{// 获取当前应用程序的版本信息,并根据修订号添加标志,返回版本字符串public string Version{get{var version = Assembly.GetExecutingAssembly().GetName().Version;var flags = "";switch (version.Revision){case 1: flags = "Beta"; break;case 2: flags = "Alpha"; break;case 3: flags = "Development Build"; break;}return $"{version.Major}.{version.Minor} {flags} (Revision {version.Build})";}}//--------------------------------------------------------------------------------------------------// 获取当前应用程序的版权信息,并返回版权字符串public string Copyright{get{return Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyCopyrightAttribute>().Copyright;}}//--------------------------------------------------------------------------------------------------// 获取当前应用程序使用的 OpenCASCADE 版本信息,并返回版本字符串public string OcctVersion{get{return $"{Occt.Helper.Version.Major}.{Occt.Helper.Version.Minor}.{Occt.Helper.Version.Maintenance}  {Occt.Helper.Version.Development}";}}//--------------------------------------------------------------------------------------------------// AboutDialog 类的构造函数,初始化窗口组件public AboutDialog(){InitializeComponent();}//--------------------------------------------------------------------------------------------------// 显示许可证链接的点击事件处理方法,执行 ShowHelpTopic 命令,打开相关的帮助主题void _ShowLicense_Click(object sender, System.Windows.RoutedEventArgs e){AppCommands.ShowHelpTopic.Execute("6d66b830-344b-4400-a50c-ba31459287d9");}//--------------------------------------------------------------------------------------------------// 打开网站链接的点击事件处理方法,通过 Process.Start 方法打开指定的网址链接void _Website_Click(object sender, System.Windows.RoutedEventArgs e){Process.Start(new ProcessStartInfo(@"https://macad3d.net") { UseShellExecute = true });}//--------------------------------------------------------------------------------------------------}
}

该代码段定义了一个名为 AboutDialog 的窗口类,用于显示关于程序的信息,包括程序版本、版权信息和 OpenCASCADE 版本信息。其主要功能包括:

  1. 定义窗口内容属性:通过属性 VersionCopyrightOcctVersion 分别获取当前程序的版本信息、版权信息和 OpenCASCADE 版本信息。

  2. 构造函数:初始化窗口组件。

  3. 点击事件处理方法_ShowLicense_Click 方法用于显示许可证链接,点击后执行 AppCommands.ShowHelpTopic 命令,打开相关的帮助主题; _Website_Click 方法用于打开网站链接,点击后通过 Process.Start 方法打开指定的网址链接。

2.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows;
using Microsoft.Win32;
using Macad.Common;
using Macad.Common.Serialization;
using Macad.Core.Topology;
using Macad.Interaction;
using Macad.Interaction.Dialogs;
using Macad.Interaction.Panels;
using Macad.Presentation;namespace Macad.Window
{// 欢迎对话框模型类,用于处理欢迎对话框的逻辑public class WelcomeDialogModel : PanelBase{// 最近使用的文件列表public List<string> MruList { get; private set; }// 示例文件夹路径public string SamplesDirectory { get; private set; }// 创建新模型命令public RelayCommand CreateNewCommand { get; }// 打开现有模型命令public RelayCommand OpenExistingCommand { get; }// 打开示例模型命令public RelayCommand OpenSampleCommand { get; }// 打开最近使用的模型命令public RelayCommand<string> OpenRecentCommand { get; }//--------------------------------------------------------------------------------------------------// 构造函数,初始化命令和属性internal WelcomeDialogModel(){OpenRecentCommand = new RelayCommand<string>(_OpenRecentCommandExecute);CreateNewCommand = new RelayCommand(_CreateNewCommandExecute);OpenExistingCommand = new RelayCommand(_OpenExistingCommandExecute);OpenSampleCommand = new RelayCommand(_OpenSampleCommandExecute, () => SamplesDirectory != null );}//--------------------------------------------------------------------------------------------------// 延迟初始化internal void DeferredInit(){// 加载最近使用的文件列表MruList = _LoadMRU();RaisePropertyChanged(nameof(MruList));// 设置示例文件夹路径SamplesDirectory = Path.Combine(PathUtils.GetAppExecutableDirectory(), "Samples");if (!Directory.Exists(SamplesDirectory)){// 尝试寻找示例文件夹SamplesDirectory = Path.GetFullPath(Path.Combine(PathUtils.GetAppExecutableDirectory(), @"..", "..", "Data", "Samples"));if (!Directory.Exists(SamplesDirectory)){SamplesDirectory = null; // 禁用命令}}}//--------------------------------------------------------------------------------------------------// 应用程序初始化完成public void AppInitialized(){}//--------------------------------------------------------------------------------------------------// 加载最近使用的文件列表List<string> _LoadMRU(){var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.Create), "Macad", "Settings", "MRU");if (!File.Exists(path)){return new List<string>();}var data = File.ReadAllText(path, Encoding.UTF8);if (data.IsNullOrEmpty()){return new List<string>();}return Serializer.Deserialize<List<string>>(data, new SerializationContext(SerializationScope.Storage));}//--------------------------------------------------------------------------------------------------// 创建新模型命令执行方法void _CreateNewCommandExecute(){// 关闭欢迎对话框并执行创建新模型命令WelcomeDialog.Current?.Close();}//--------------------------------------------------------------------------------------------------// 打开示例模型命令执行方法void _OpenSampleCommandExecute(){// 打开示例模型文件对话框,并加载选择的示例模型var fileName = _ShowOpenFileDialog(SamplesDirectory);if (fileName != null){_BeginInvoke(() =>{InteractiveContext.Current?.DocumentController?.OpenModel(fileName);});WelcomeDialog.Current?.Close();}}//--------------------------------------------------------------------------------------------------// 打开现有模型命令执行方法void _OpenExistingCommandExecute(){// 打开现有模型文件对话框,并加载选择的现有模型var fileName = _ShowOpenFileDialog(null);if (fileName != null){_BeginInvoke(() =>{InteractiveContext.Current?.DocumentController?.OpenModel(fileName);});WelcomeDialog.Current?.Close();}}//--------------------------------------------------------------------------------------------------// 打开最近使用的模型命令执行方法void _OpenRecentCommandExecute(string fileName){// 如果文件不存在,显示错误对话框并从最近使用列表中移除该文件if (!File.Exists(fileName)){bool remove = false;_BeginInvoke(() =>{remove = ErrorDialogs.RecentFileNotFound(fileName);if(remove){InteractiveContext.Current?.DocumentController?.RemoveFromMruList(fileName);MruList = _LoadMRU();RaisePropertyChanged(nameof(MruList));}});return;}// 打开最近使用的模型文件using (new WaitCursor()){WelcomeDialog.Current.Cursor = Cursors.Wait;_BeginInvoke(() => { InteractiveContext.Current?.DocumentController?.OpenFile(fileName, false); });}WelcomeDialog.Current?.Close();}//--------------------------------------------------------------------------------------------------// 显示打开文件对话框string _ShowOpenFileDialog(string path){var dlg = new OpenFileDialog(){Title = "Open Model...",CheckFileExists = true,Filter = "Macad3D Models|*." + Model.FileExtension,DefaultExt = Model.FileExtension,InitialDirectory = path ?? ""};var result = dlg.ShowDialog(WelcomeDialog.Current);return (bool) result ? dlg.FileName : null;}//--------------------------------------------------------------------------------------------------// 在 UI 线程上执行操作void _BeginInvoke(Action callback){Application.Current.Dispatcher.BeginInvoke(callback);}}
}

该代码定义了一个名为 WelcomeDialogModel 的类,用于处理欢迎对话框的逻辑。主要功能包括:

  1. 属性定义:定义了最近使用的文件列表 (MruList) 和示例文件夹路径 (SamplesDirectory)。

  2. 命令定义:定义了创建新模型、打开现有模型、打开示例模型和打开最近使用的模型的命令 (CreateNewCommand, OpenExistingCommand, OpenSampleCommand, OpenRecentCommand)。

  3. 构造函数:初始化命令和属性。

  4. DeferredInit 方法:延迟初始化,用于加载最近使用的文件列表和设置示例文件夹路径。

  5. AppInitialized 方法:应用程序初始化完成后执行的方法。

  6. _LoadMRU 方法:加载最近使用的文件列表。

  7. 命令执行方法:分别处理创建新模型、打开示例模型、打开现有模型、打开最近使用的模型的命令。

  8. _ShowOpenFileDialog 方法:显示打开文件对话框,用于选择模型文件。

  9. _BeginInvoke 方法:在 UI 线程上执行操作。

3.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using Fluent;
using Macad.Common;
using Macad.Common.Interop;
using Macad.Core;
using Macad.Interaction;
using Macad.Interaction.Dialogs;
using Macad.Presentation;namespace Macad.Window
{/// <summary>/// 主窗口类,继承自 RibbonWindow/// </summary>public partial class MainWindow : RibbonWindow{// 当前主窗口实例public static MainWindow Current { get; private set; }//--------------------------------------------------------------------------------------------------// 主窗口模型public MainWindowModel Model => (MainWindowModel)DataContext;//--------------------------------------------------------------------------------------------------// 3D 导航器实例public SpaceNavigator SpaceNavigator { get; } = new SpaceNavigator();//--------------------------------------------------------------------------------------------------// 构造函数,初始化窗口并绑定事件public MainWindow(MainWindowModel model){Current = this;DataContext = model;// 绑定窗口加载、卸载、关闭等事件Loaded += _MainWindow_Loaded;Unloaded += _MainWindow_Unloaded;Closing += _MainWindow_Closing;SourceInitialized += _MainWindow_OnSourceInitialized;DragOver += _MainWindow_DragOver;Drop += _MainWindow_Drop;KeyDown += _MainWindow_KeyDown;InitializeComponent();ScreenTip.HelpPressed += _ScreenTipOnHelpPressed;}//--------------------------------------------------------------------------------------------------#region Window Callbacks// 窗口加载完成事件处理方法void _MainWindow_Loaded(object sender, RoutedEventArgs e){// 初始化 3D 导航器SpaceNavigator.Init(this);// 执行应用程序初始化命令和启动命令AppCommands.InitApplication.Execute();Dispatcher.CurrentDispatcher.BeginInvoke(AppCommands.RunStartupCommands.Execute, DispatcherPriority.Loaded);// 设置焦点到 Viewport 控件Docking.Viewport.Focus();}//--------------------------------------------------------------------------------------------------// 窗口卸载完成事件处理方法void _MainWindow_Unloaded(object sender, RoutedEventArgs e){// 卸载 3D 导航器SpaceNavigator.DeInit();}//--------------------------------------------------------------------------------------------------// 窗口关闭事件处理方法void _MainWindow_Closing(object sender, CancelEventArgs e){// 准备关闭窗口AppCommands.PrepareWindowClose.Execute(e);// 如果不取消关闭并且不在沙盒中,则保存窗口位置和应用程序设置if(!e.Cancel && !AppContext.IsInSandbox){WindowPlacement.SaveWindowPlacement(MainWindow.Current, "MainWindowPlacement");AppContext.Current.SaveSettings();}}//--------------------------------------------------------------------------------------------------// 键盘按下事件处理方法void _MainWindow_KeyDown(object sender, KeyEventArgs e){if (e.OriginalSource is TextBoxBase)return;// 在模型中处理全局键盘按下事件e.Handled = Model.GlobalKeyDown(e);}//--------------------------------------------------------------------------------------------------// 窗口源初始化事件处理方法void _MainWindow_OnSourceInitialized(object sender, EventArgs e){// 启用窗口拖放文件功能var hwnd = new WindowInteropHelper(this).Handle;Win32Api.DragAcceptFiles(hwnd, true);var hwndSource = PresentationSource.FromVisual(this) as HwndSource;Debug.Assert(hwndSource != null, nameof(hwndSource) + " != null");hwndSource.AddHook(WndProc);// 加载窗口位置if (!AppContext.IsInSandbox){WindowPlacement.LoadWindowPlacement(this, "MainWindowPlacement");}else{this.Left = 0;this.Top = 0;}}//--------------------------------------------------------------------------------------------------// 窗口消息处理方法IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled){switch (msg){case Win32Api.WM_DROPFILES:{handled = true;const int maxPath = 260;var hDrop = wParam;var count = Win32Api.DragQueryFile(hDrop, 0xFFFFFFFF, null, 0);if (count > 0)count = 1; // Currently, we only import the firstfor (uint i = 0; i < count; i++){int size = (int)Win32Api.DragQueryFile(hDrop, i, null, 0);var filename = new StringBuilder(size + 1);Win32Api.DragQueryFile(hDrop, i, filename, maxPath);_ImportDroppedFile(filename.ToString());}Win32Api.DragFinish(hDrop);break;}case Win32Api.WM_ENABLE:{bool bIsEnabled = wParam.ToInt32() == 1;Docking.Viewport.SetWindowEnabled(bIsEnabled);break;}}return IntPtr.Zero;}//--------------------------------------------------------------------------------------------------#endregion#region Drop Files// 提取拖放文件的文件路径string _ExtractDropFile(DragEventArgs e){if (e.Data.GetDataPresent(DataFormats.FileDrop)){// 获取拖放的文件路径var files = (string[]) e.Data.GetData(DataFormats.FileDrop);if (files != null){var filePath = files.First();if(ExchangeCommands.ImportDroppedFile.CanExecute(filePath)){return filePath;}}}return null;}//--------------------------------------------------------------------------------------------------// 拖放事件处理方法void _MainWindow_Drop(object sender, DragEventArgs e){if (e.Handled)return;_ImportDroppedFile(_ExtractDropFile(e));}//--------------------------------------------------------------------------------------------------// 拖放过程中事件处理方法void _MainWindow_DragOver(object sender, DragEventArgs e){// 设置拖放效果if (ExchangeCommands.ImportDroppedFile.CanExecute(_ExtractDropFile(e))){e.Effects = DragDropEffects.None;e.Handled = true;}}//--------------------------------------------------------------------------------------------------// 导入拖放文件void _ImportDroppedFile(string filePath){if (filePath.IsNullOrEmpty() || !ExchangeCommands.ImportDroppedFile.CanExecute(filePath))return;Activate();ExchangeCommands.ImportDroppedFile.Execute(filePath);}//--------------------------------------------------------------------------------------------------#endregion#region Help// 应用程序命令帮助执行事件处理方法void _ApplicationCommandsHelp_Executed(object sender, ExecutedRoutedEventArgs e){string topicId = e.Parameter as string;DependencyObject currentObj = FocusManager.GetFocusedElement(e.Source as DependencyObject) as DependencyObject;while (topicId == null && currentObj != null){topicId = Help.GetTopicId(currentObj);currentObj = LogicalTreeHelper.GetParent(currentObj);}AppCommands.ShowHelpTopic.Execute(topicId);}//--------------------------------------------------------------------------------------------------// 屏幕提示帮助按下事件处理方法void _ScreenTipOnHelpPressed(object sender, ScreenTipHelpEventArgs e){AppCommands.ShowHelpTopic.Execute(e.HelpTopic as string);}//--------------------------------------------------------------------------------------------------#endregion}
}

这段代码定义了主窗口 MainWindow 类,该类继承自 RibbonWindow,负责处理主窗口的交互逻辑。其中涉及了窗口的加载、卸载、关闭、按键、拖放文件等事件处理,以及对空间导航设备的初始化、窗口消息处理等功能。

4.

using System.Windows.Input;
using Macad.Core;
using Macad.Interaction;namespace Macad.Window
{// MainWindowModel 类,用于定义主窗口的数据模型public class MainWindowModel{// 获取当前交互上下文的属性public virtual InteractiveContext Context{get { return InteractiveContext.Current; }}//--------------------------------------------------------------------------------------------------// 构造函数,初始化 MainWindowModel 实例public MainWindowModel(){// 订阅应用程序消息处理器的进度消息事件AppContext.Current.MessageHandler.ProgressMessage += _MessageHandler_ProgressMessage;}//--------------------------------------------------------------------------------------------------// 进度消息事件处理方法void _MessageHandler_ProgressMessage(object sender, MessageHandler.ProgressMessageEventArgs e){// 根据消息原因设置鼠标光标样式switch (e.Reason){case MessageHandler.ProgressMessageEventReason.ProcessingStarted:Mouse.OverrideCursor = Interaction.Cursors.Wait; // 显示等待光标break;case MessageHandler.ProgressMessageEventReason.ProcessingStopped:Mouse.OverrideCursor = null; // 恢复默认光标break;}}//--------------------------------------------------------------------------------------------------// 全局按键事件处理方法public bool GlobalKeyDown(KeyEventArgs keyEventArgs){// 检查是否按下了应用程序或工作空间范围内的快捷键return AppContext.Current.ShortcutHandler.KeyPressed(ShortcutScope.Application, keyEventArgs.Key, Keyboard.Modifiers)|| InteractiveContext.Current.ShortcutHandler.KeyPressed(ShortcutScope.Workspace, keyEventArgs.Key, Keyboard.Modifiers);}//--------------------------------------------------------------------------------------------------}
}

这段代码定义了 MainWindowModel 类,用于定义主窗口的数据模型。其中包括获取当前交互上下文的属性、订阅应用程序消息处理器的进度消息事件、处理进度消息事件、处理全局按键事件等功能。

5.

using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using Fluent;
using Macad.Interaction;
using Macad.Presentation;namespace Macad.Window
{/// <summary>/// MainWindowRibbon 类,用于定义主窗口的 Fluent Ribbon 控件的交互逻辑/// </summary>public partial class MainWindowRibbon : UserControl{// 构造函数,初始化 MainWindowRibbon 实例public MainWindowRibbon(){InitializeComponent();// 设置 Fluent Ribbon 控件的本地化文化为不可变的英文文化RibbonLocalization.Current.Culture = CultureInfo.InvariantCulture;}//--------------------------------------------------------------------------------------------------// 当 ContextualGroup 的可见性发生变化时触发的事件处理方法void _ContextualGroup_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e){// 如果上一个值为 false,当前值为 true,则执行以下操作if ((!(bool)e.OldValue) && (bool)e.NewValue){var group = sender as RibbonContextualTabGroup; // 获取 ContextualGroupvar tabItem = group?.Items.FirstOrDefault(); // 获取第一个选项卡项if (tabItem != null){tabItem.IsSelected = true; // 选中第一个选项卡项}}}//--------------------------------------------------------------------------------------------------// 在数据传输事件 SourceUpdated 发生时关闭菜单的方法void _CloseMenuOnSourceUpdated(object sender, DataTransferEventArgs e){// 查找逻辑父级为 DropDownButton 的元素var element = PresentationHelper.FindLogicalParent<DropDownButton>(sender as FrameworkElement);if (element != null){element.IsDropDownOpen = false; // 关闭下拉菜单}}//--------------------------------------------------------------------------------------------------// 最近文件菜单项点击事件处理方法void _RecentFilesMenuItem_Click(object sender, RoutedEventArgs e){RibbonFileMenu.IsDropDownOpen = false; // 关闭文件菜单下拉菜单}//--------------------------------------------------------------------------------------------------// 键盘按键事件处理方法void _KeyDown(object sender, KeyEventArgs e){if (e.OriginalSource is TextBoxBase)return;// 将按键事件转发到工作空间处理e.Handled = AppContext.Current.ShortcutHandler.KeyPressed(ShortcutScope.Workspace, e.Key, Keyboard.Modifiers);}//--------------------------------------------------------------------------------------------------}
}

这段代码定义了 MainWindowRibbon 类,用于定义主窗口的 Fluent Ribbon 控件的交互逻辑。其中包括设置本地化文化、处理 ContextualGroup 的可见性变化、关闭菜单的方法、处理最近文件菜单项点击事件以及处理键盘按键事件等功能

6.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace Macad.Window
{/// <summary>/// MainWindowStatusBar 类,用于定义主窗口的状态栏 UserControl 的交互逻辑/// </summary>public partial class MainWindowStatusBar : UserControl{// 构造函数,初始化 MainWindowStatusBar 实例public MainWindowStatusBar(){InitializeComponent();}}
}

这段代码定义了 MainWindowStatusBar 类,用于定义主窗口的状态栏 UserControl 的交互逻辑。其中包括初始化 MainWindowStatusBar 实例的构造函数。

7.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Macad.Interaction;
using Macad.Interaction.Dialogs;
using Macad.Presentation;namespace Macad.Window
{// ViewportViewModel 类,实现了 INotifyPropertyChanged 接口,用于处理视口相关的视图模型逻辑public class ViewportViewModel : INotifyPropertyChanged{#region Properties// UpdateMessage 属性,用于显示更新消息public string UpdateMessage{get { return _UpdateMessage; }private set{if (_UpdateMessage != value){_UpdateMessage = value;RaisePropertyChanged();}}}//--------------------------------------------------------------------------------------------------#endregion#region Members and n'torstring _UpdateMessage; // 存储更新消息VersionCheckInfo _UpdateInfo; // 存储更新信息// 构造函数,初始化 ViewportViewModel 实例internal ViewportViewModel(){UpdateCommand = new RelayCommand(_UpdateExecute);DismissUpdateCommand = new RelayCommand(_DismissUpdateExecute);VersionCheck.UpdateAvailable += _VersionCheck_UpdateAvailable;}//--------------------------------------------------------------------------------------------------// 析构函数,取消订阅更新事件~ViewportViewModel(){VersionCheck.UpdateAvailable -= _VersionCheck_UpdateAvailable;}//--------------------------------------------------------------------------------------------------#endregion#region Update Info// 当更新可用时触发的事件处理方法void _VersionCheck_UpdateAvailable(object sender, VersionCheckInfo info){_UpdateInfo = info;UpdateMessage = "A new version of Macad|3D is available for download."; // 更新消息RaisePropertyChanged(nameof(UpdateMessage));}//--------------------------------------------------------------------------------------------------// 执行更新命令的命令对象public RelayCommand UpdateCommand { get; }// 关闭更新消息的命令对象public RelayCommand DismissUpdateCommand { get; }//--------------------------------------------------------------------------------------------------// 更新执行方法void _UpdateExecute(){_DismissUpdateExecute(); // 关闭更新消息// 如果存在更新信息且更新可用if (_UpdateInfo != null && _UpdateInfo.UpdateAvailable){bool disableCheck = false;// 显示更新通知对话框,提示用户是否下载更新if (Dialogs.InformUpdateAvailable(_UpdateInfo.UpdateVersion, _UpdateInfo.UpdateUrl, ref disableCheck)){// 启动默认浏览器并打开更新链接Process.Start(new ProcessStartInfo(_UpdateInfo.UpdateUrl) { UseShellExecute = true });}// 根据用户选择更新自动检查设置VersionCheck.IsAutoCheckEnabled = !disableCheck;}}//--------------------------------------------------------------------------------------------------// 关闭更新消息执行方法void _DismissUpdateExecute(){UpdateMessage = ""; // 清空更新消息VersionCheck.ResetAvailability(); // 重置更新可用性}//--------------------------------------------------------------------------------------------------#endregion#region INotifyPropertyChanged// PropertyChanged 事件,用于通知属性值更改public event PropertyChangedEventHandler PropertyChanged;// 属性更改通知方法protected virtual void RaisePropertyChanged([CallerMemberName] String propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}//--------------------------------------------------------------------------------------------------#endregion}
}

这段代码定义了 ViewportViewModel 类,实现了 INotifyPropertyChanged 接口,用于处理视口相关的视图模型逻辑。其中包括了处理更新消息、执行更新命令和关闭更新消息的逻辑。

8.

using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using Macad.Common;
using Macad.Common.Interop;
using Macad.Presentation;namespace Macad.Window
{/// <summary>/// App.xaml 的交互逻辑/// </summary>public partial class App : Application{// 所有 WPF 应用程序应在单线程单元 (STA) 线程上执行[STAThread]protected override void OnStartup(StartupEventArgs e){// 启用指针支持,用于兼容不同平台的输入设备System.AppContext.SetSwitch("Switch.System.Windows.Input.Stylus.EnablePointerSupport", true);// 设置当前线程的区域性为英文CultureInfo culture = new CultureInfo("en");Thread.CurrentThread.CurrentCulture = culture;Thread.CurrentThread.CurrentUICulture = culture;CultureInfo.DefaultThreadCurrentCulture = culture;CultureInfo.DefaultThreadCurrentUICulture = culture;// 获取应用程序基本路径并初始化崩溃处理器string baseDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);CrashHandler.Init(baseDir);// 解析命令行参数var cmdLine = new CommandLine(e.Args);// 在初始化期间显示欢迎对话框bool bSkipWelcome = cmdLine.NoWelcomeDialog || cmdLine.HasPathToOpen || cmdLine.HasScriptToRun;if (!bSkipWelcome){WelcomeDialog.ShowAsync();}// 为 Shell 功能设置 AppUserModelID,如 JumpList、任务栏分组等Win32Api.SetCurrentProcessExplicitAppUserModelID("Macad.1");// 创建实例互斥量CreateInstanceMutexes();// 初始化 OCCT// 初始化全局事件处理器和剪贴板// 初始化上下文AppContext.Initialize(cmdLine);// 启动主窗口MainWindow = new MainWindow(new MainWindowModel());WelcomeDialog.Current?.SetMainWindow(MainWindow);MainWindow.Show();ShutdownMode = ShutdownMode.OnMainWindowClose;base.OnStartup(e);}//--------------------------------------------------------------------------------------------------protected override void OnExit(ExitEventArgs e){base.OnExit(e);AppContext.Current?.Dispose();}//--------------------------------------------------------------------------------------------------/** 创建两个互斥量,由安装程序/卸载程序检查以查看程序是否仍在运行。* 一个互斥量在全局名称空间中创建(这使得在 Windows XP 中可以跨用户会话访问互斥量);* 另一个互斥量在会话名称空间中创建(因为 Windows NT 4.0 TSE 之前的版本没有全局名称空间,并且不支持 'Global\' 前缀)。*/void CreateInstanceMutexes(){const string mutexName = "MacadInstanceRunning";/* 默认情况下,Windows NT 上创建的互斥量只能由运行进程的用户访问。* 我们需要使我们的互斥量对所有用户都可访问,以便在 Windows XP 中可以跨用户会话进行互斥量检测。* 为此,我们使用一个具有空 DACL 的安全描述符。*/IntPtr ptrSecurityDescriptor = IntPtr.Zero;try{var securityDescriptor = new Win32Api.SECURITY_DESCRIPTOR();Win32Api.InitializeSecurityDescriptor(out securityDescriptor, Win32Api.SECURITY_DESCRIPTOR_REVISION);Win32Api.SetSecurityDescriptorDacl(ref securityDescriptor, true, IntPtr.Zero, false);ptrSecurityDescriptor = Marshal.AllocCoTaskMem(Marshal.SizeOf(securityDescriptor));Marshal.StructureToPtr(securityDescriptor, ptrSecurityDescriptor, false);var securityAttributes = new Win32Api.SECURITY_ATTRIBUTES();securityAttributes.nLength = Marshal.SizeOf(securityAttributes);securityAttributes.lpSecurityDescriptor = ptrSecurityDescriptor;securityAttributes.bInheritHandle = false;if (Win32Api.CreateMutex(ref securityAttributes, false, mutexName) == IntPtr.Zero|| Win32Api.CreateMutex(ref securityAttributes, false, @"Global\" + mutexName) == IntPtr.Zero){var lastError = Win32Error.GetLastError();// 如果得到 ERROR_ALREADY_EXISTS 值,则已经有另一个实例正在运行。// 这是正常的,不是错误。if (lastError != Win32Error.ERROR_ALREADY_EXISTS){Console.WriteLine($"InstanceMutex creation failed: {Marshal.GetLastWin32Error()}");}}}catch (Exception e){Console.WriteLine(e);}if(ptrSecurityDescriptor != IntPtr.Zero)Marshal.FreeCoTaskMem(ptrSecurityDescriptor);}}
}

这段代码实现了 App 类,该类是 WPF 应用程序的入口点,并且继承自 Application。其主要功能包括设置应用程序的一些全局属性、处理程序生命周期事件、初始化应用程序上下文、创建主窗口、设置互斥量等。

这篇关于macad解析macad-windows篇的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/726060

相关文章

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

深度解析Python中递归下降解析器的原理与实现

《深度解析Python中递归下降解析器的原理与实现》在编译器设计、配置文件处理和数据转换领域,递归下降解析器是最常用且最直观的解析技术,本文将详细介绍递归下降解析器的原理与实现,感兴趣的小伙伴可以跟随... 目录引言:解析器的核心价值一、递归下降解析器基础1.1 核心概念解析1.2 基本架构二、简单算术表达

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置

从原理到实战解析Java Stream 的并行流性能优化

《从原理到实战解析JavaStream的并行流性能优化》本文给大家介绍JavaStream的并行流性能优化:从原理到实战的全攻略,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的... 目录一、并行流的核心原理与适用场景二、性能优化的核心策略1. 合理设置并行度:打破默认阈值2. 避免装箱

Maven中生命周期深度解析与实战指南

《Maven中生命周期深度解析与实战指南》这篇文章主要为大家详细介绍了Maven生命周期实战指南,包含核心概念、阶段详解、SpringBoot特化场景及企业级实践建议,希望对大家有一定的帮助... 目录一、Maven 生命周期哲学二、default生命周期核心阶段详解(高频使用)三、clean生命周期核心阶

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

Java Scanner类解析与实战教程

《JavaScanner类解析与实战教程》JavaScanner类(java.util包)是文本输入解析工具,支持基本类型和字符串读取,基于Readable接口与正则分隔符实现,适用于控制台、文件输... 目录一、核心设计与工作原理1.底层依赖2.解析机制A.核心逻辑基于分隔符(delimiter)和模式匹

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装

深度解析Python yfinance的核心功能和高级用法

《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?