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

相关文章

Oracle数据库常见字段类型大全以及超详细解析

《Oracle数据库常见字段类型大全以及超详细解析》在Oracle数据库中查询特定表的字段个数通常需要使用SQL语句来完成,:本文主要介绍Oracle数据库常见字段类型大全以及超详细解析,文中通过... 目录前言一、字符类型(Character)1、CHAR:定长字符数据类型2、VARCHAR2:变长字符数

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

SpringCloud动态配置注解@RefreshScope与@Component的深度解析

《SpringCloud动态配置注解@RefreshScope与@Component的深度解析》在现代微服务架构中,动态配置管理是一个关键需求,本文将为大家介绍SpringCloud中相关的注解@Re... 目录引言1. @RefreshScope 的作用与原理1.1 什么是 @RefreshScope1.

Java并发编程必备之Synchronized关键字深入解析

《Java并发编程必备之Synchronized关键字深入解析》本文我们深入探索了Java中的Synchronized关键字,包括其互斥性和可重入性的特性,文章详细介绍了Synchronized的三种... 目录一、前言二、Synchronized关键字2.1 Synchronized的特性1. 互斥2.

Java的IO模型、Netty原理解析

《Java的IO模型、Netty原理解析》Java的I/O是以流的方式进行数据输入输出的,Java的类库涉及很多领域的IO内容:标准的输入输出,文件的操作、网络上的数据传输流、字符串流、对象流等,这篇... 目录1.什么是IO2.同步与异步、阻塞与非阻塞3.三种IO模型BIO(blocking I/O)NI

Python 中的异步与同步深度解析(实践记录)

《Python中的异步与同步深度解析(实践记录)》在Python编程世界里,异步和同步的概念是理解程序执行流程和性能优化的关键,这篇文章将带你深入了解它们的差异,以及阻塞和非阻塞的特性,同时通过实际... 目录python中的异步与同步:深度解析与实践异步与同步的定义异步同步阻塞与非阻塞的概念阻塞非阻塞同步

Redis中高并发读写性能的深度解析与优化

《Redis中高并发读写性能的深度解析与优化》Redis作为一款高性能的内存数据库,广泛应用于缓存、消息队列、实时统计等场景,本文将深入探讨Redis的读写并发能力,感兴趣的小伙伴可以了解下... 目录引言一、Redis 并发能力概述1.1 Redis 的读写性能1.2 影响 Redis 并发能力的因素二、

Spring MVC使用视图解析的问题解读

《SpringMVC使用视图解析的问题解读》:本文主要介绍SpringMVC使用视图解析的问题解读,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring MVC使用视图解析1. 会使用视图解析的情况2. 不会使用视图解析的情况总结Spring MVC使用视图

Windows Server服务器上配置FileZilla后,FTP连接不上?

《WindowsServer服务器上配置FileZilla后,FTP连接不上?》WindowsServer服务器上配置FileZilla后,FTP连接错误和操作超时的问题,应该如何解决?首先,通过... 目录在Windohttp://www.chinasem.cnws防火墙开启的情况下,遇到的错误如下:无法与