当前位置:网站首页>Maui learning road (III) -- in depth discussion of winui3
Maui learning road (III) -- in depth discussion of winui3
2022-07-02 16:02:00 【Dotnet cross platform】
Maui The way of learning --- Winui3 In-depth discussion
Study Maui
It's been a while , As it goes deeper , Yes Maui
Have some preliminary understanding .
We all know Maui
In order to maintain the native features of the platform , So in each platform, the native development framework of the platform itself is used , If in Windows
The system uses Winui3
As UI
frame ,Mac
The platform uses UIKit
As UI
frame ,( I would like to call it “ Dolls ”
Or it makes a layer for different platforms “ abstract ”
), So if you operate directly Maui
An attribute or method of the object of is actually transferred to the platform related attribute or method behind its back .
With this understanding, we will deeply understand that if I want to change something , In fact, you can also directly operate the platform related methods , Operation is not necessary Maui
object ( If Maui
No such capability is provided , You can only do this ).
Doing it Windows
When developing desktop programs , We often have such needs , Yours exe
Only one program can be run at a time ( Single case ), You really want the program to open on the full screen , Others cannot close it easily ( Usually in the industrial field, such demand is great ).
Based on the above requirements , Let's have a deep understanding and study , How to achieve :
use first Maui
Every project created by the template has a Platforms
The catalog of , This is essentially a project set corresponding to multiple platforms ( stay Xamarin
If you need to build a real cross platform program , In fact, it can't be done , You need to go through Xamarin.Form
Templates for creating portals for different platforms , Then extract the common platform independent logic as a shared resource across platforms ), With this design Maui
It really realizes the compilation and running of a code everywhere , You don't need to make any special changes to the project when compiling on other platforms ( At present, we support Mac
、Windows
Platform compilation )( There is no further discussion here , If you want to know Maui
and Xamarin
See this video for engineering differences :.NET MAUI Cross platform development collection _ Bili, Bili _bilibili[1])

Secondly, for Maui
Executable works ( Not dll
) Come on , The real entry of the program corresponding to the platform is not MauiProgram
or Maui
Of Application
, He is actually Platforms
Under the corresponding platform Main Or is it App, For example, yes. Window
Come on ,Maui
The real entry to start the program is Platforms/Windows/App This object .

Window Single instance implementation
With the above understanding as the basis , Then implementing a singleton is very simple , stay Wpf
perhaps Winform
Have done the same design on , Now you just need to move it ( stay Wpf
or Winform
There are many ways to implement singletons , The most common is to use Mutex
) Please refer to the implementation method : Snack bar - .NET MAUI Community Toolkit - .NET Community Toolkit | Microsoft Docs [2] stay Platform/Windows/App.xaml.cs Add single case examination
public partial class App : MauiWinUIApplication
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
}
static Mutex? __SingleMutex;
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
if (!IsSingleInstance())
{
//Process.GetCurrentProcess().Kill();
Environment.Exit(0);
return;
}
base.OnLaunched(args);
}
static bool IsSingleInstance()
{
const string applicationId = "813342EB-7796-4B13-98F1-14C99E778C6E";
__SingleMutex = new Mutex(false, applicationId);
GC.KeepAlive(__SingleMutex);
try
{
return __SingleMutex.WaitOne(0, false);
}
catch (Exception)
{
__SingleMutex.ReleaseMutex();
return __SingleMutex.WaitOne(0, false);
}
}
}
Implement a borderless form
Before that, I actually wrote an article Maui stay windows How to implement borderless on , Interested students can check it out ( link :Window Form settings ).Maui
In fact, it provides a person named Window
The type of , Unfortunately, there are no properties related to setting windows in this type ( such as : wide , high , Background color and so on , In addition, it cannot be modified Style
To change the style ), Obviously Maui
It is a cross platform design , Because there is no so-called concept of window size on the mobile end , Usually it is full screen . If we need to modify the form , Then you need to get Window
Managed behind the object Native Object only
obtain Native object
Method 1: register Maui Provided lifecycle functions
Relevant program lifecycle notifications will be pushed on different platforms ( Here you can get the platform related operation objects, including the corresponding Application
,Window
), There are some disadvantages of using this method when using multi form scheme , You can't locate which is the main window ( Of course, the first creation must be the main form ), Details please see : Application life cycle - .NET MAUI | Microsoft Docs[3]( If you want to know the details, you can watch this video :.NET MAUI BLAZOR Life cycle _ Bili, Bili _bilibili[4])
Method 2: visit Window Under the Handler attribute
Maui
Window
There is such a property in the type Handler
( The type is IElementHandler
, The implementation type is ElementHandler
)( be-all Maui
Control objects all have this property ), This attribute records the Native Mapping objects ( If you want to modify native
The appearance of the object , You can access the attributes of his subordinates PlatformView
( Convert it into the corresponding platform native
object ))( Notice at the beginning new Window
Object time Handler
The object doesn't exist , You can register HandlerChanged
Events capture his changes )( stay Winodw
platform PlatformView
The object is Microsoft.UI.Xaml.Window
type )
Learning is necessary Winui3 Related knowledge
from Winui
At the beginning, Microsoft brought a new design of windows , If you need to implement such as window size modification , Title bar modification , You need to learn the following knowledge to realize functions such as full screen :
Custom title bar
link : Title bar customization - Windows apps | Microsoft Docs[5]
AppWindow
This is a Win10
The window operation object introduced later , Learning links : Use AppWindow Class to display the auxiliary window of the application - Windows apps | Microsoft Docs[6] as well as AppWindow Class (Microsoft.UI.Windowing) - Windows App SDK | Microsoft Docs[7]
Be careful : There are deviations in the introduction of learning materials related to the official website in different documents , Mainly part of the design is the old design , Not updated in time , Please use Windows App SDK 1.1 The version shall prevail
By learning the above knowledge , We can customize some functions
Change the window size :
var winuiWindow = Window.Handler?.PlatformView as MicrosoftuiXaml.Window;
if (winuiWindow is null)
return;
var appWindow = winuiWindow.GetAppWindow();
if (appWindow is null)
return;
var displyArea = MicrosoftuiWindowing.DisplayArea.Primary;
double scalingFactor = winuiWindow.GetDisplayDensity();
var width = 800 * scalingFactor;
var height = 600 * scalingFactor;
double startX = (displyArea.WorkArea.Width - width) / 2.0;
double startY = (displyArea.WorkArea.Height - height) / 2.0;
appWindow.MoveAndResize(new((int)startX, (int)startY, (int)width, (int)height), displyArea);
Maximize ( Use Win32 news ):
var winuiWindow = Window.Handler?.PlatformView as MicrosoftuiXaml.Window;
if (winuiWindow is null)
return;
var windowHanlde = winuiWindow.GetWindowHandle();
User32.PostMessage(windowHanlde, WindowMessage.WM_SYSCOMMAND, new IntPtr((int)SysCommands.SC_MINIMIZE), IntPtr.Zero);
To minimize the ( Use Win32 news ):
var winuiWindow = Window.Handler?.PlatformView as MicrosoftuiXaml.Window;
if (winuiWindow is null)
return;
var windowHanlde = winuiWindow.GetWindowHandle();
User32.PostMessage(windowHanlde, WindowMessage.WM_SYSCOMMAND, new IntPtr((int)SysCommands.SC_MINIMIZE), IntPtr.Zero);
Full screen :
var winuiWindow = Window.Handler?.PlatformView as MicrosoftuiXaml.Window;
if (winuiWindow is null)
return;
var appWindow = winuiWindow.GetAppWindow();
if (appWindow is null)
return;
// Pay attention to Maui Extension is enabled by default TitleBar( Title bar fusion mode ?) So first remove Otherwise, the full screen will still appear Turn off, etc
// Although the title bar fusion mode is turned off , But there will still be something like a title bar when the screen is full , If it needs to be processed, it needs to be deeply customized ( You can check mine github project )
winuiWindow.ExtendsContentIntoTitleBar = false;
appWindow.SetPresenter(MicrosoftuiWindowing.AppWindowPresenterKind.FullScreen);
modify
Maui
Default title bar color :
var winuiWindow = Window.Handler?.PlatformView as MicrosoftuiXaml.Window;
if (winuiWindow is null)
return;
var application = MicrosoftuiXaml.Application.Current;
var res = application.Resources;
// Seeing here, you must wonder why it is like this , If you're interested , You can refer to Winui3 Source code
res["WindowCaptionBackground"] = new MicrosoftuixmlMedia.SolidColorBrush(Microsoftui.Colors.Red);
// After modifying the title bar, you need to actively refresh it to take effect ( Otherwise, you need to minimize it manually )
TriggertTitleBarRepaint();
above Demo
Have been uploaded Github Address :WPFDevelopersOrg/Demo[8] , Please refer to MauiApp1
This demo
.
Finally, I will put one that I have achieved so far Maui
Win11
The demonstration effect of :
The project has been uploaded github Address :WPFDevelopersOrg/MauiToolkit[9]
Reference material
[1]
.NET MAUI Cross platform development collection _ Bili, Bili _bilibili: https://www.bilibili.com/video/BV1VW4y1k7Bk?p=3
[2]Snack bar - .NET MAUI Community Toolkit - .NET Community Toolkit | Microsoft Docs : https://docs.microsoft.com/zh-cn/dotnet/communitytoolkit/maui/alerts/snackbar
[3]Application life cycle - .NET MAUI | Microsoft Docs: https://docs.microsoft.com/zh-cn/dotnet/maui/fundamentals/app-lifecycle
[4].NET MAUI BLAZOR Life cycle _ Bili, Bili _bilibili: https://www.bilibili.com/video/BV1vA4y1d74A?spm_id_from=333.999.0.0
[5]Title bar customization - Windows apps | Microsoft Docs: https://docs.microsoft.com/zh-cn/windows/apps/develop/title-bar?tabs=winui3
[6]Use AppWindow Class to display the auxiliary window of the application - Windows apps | Microsoft Docs: https://docs.microsoft.com/zh-cn/windows/apps/design/layout/app-window
[7]AppWindow Class (Microsoft.UI.Windowing) - Windows App SDK | Microsoft Docs: https://docs.microsoft.com/zh-CN/windows/windows-app-sdk/api/winrt/microsoft.ui.windowing.appwindow?view=windows-app-sdk-1.1
[8]WPFDevelopersOrg/Demo: https://github.com/WPFDevelopersOrg/Demo
[9]WPFDevelopersOrg/MauiToolkit: https://github.com/WPFDevelopersOrg/MauiToolkit
边栏推荐
- 解决BASE64Encoder报错的问题
- After the win10 system is upgraded for a period of time, the memory occupation is too high
- /Bin/ld: cannot find -lgssapi_ krb5
- Tree binary search tree
- 【小白聊云】中小企业容器化改造建议
- 数仓中的维度表与事实表
- /Bin/ld: cannot find -lcrypto
- Practice of constructing ten billion relationship knowledge map based on Nebula graph
- JS learning notes - first acquaintance
- Another graduation season
猜你喜欢
图数据库|Nebula Graph v3.1.0 性能报告
JS learning notes - variables
智联招聘的基于 Nebula Graph 的推荐实践分享
爱可可AI前沿推介(7.2)
mysql 计算经纬度范围内的数据
如何实现十亿级离线 CSV 导入 Nebula Graph
Processing gzip: stdin: not in gzip format: child returned status 1tar: error is not recoverable: exitin
Storage, reading and writing of blood relationship data of Nepal Graph & Data Warehouse
HMS core machine learning service helps zaful users to shop conveniently
【5G NR】RRC连接释放
随机推荐
Practice of constructing ten billion relationship knowledge map based on Nebula graph
[5g NR] RRC connection release
Solve * * warning * *: your ApplicationContext is unlikely to start due to a @componentscan of the defau
隐藏在 Nebula Graph 背后的星辰大海
(Wanzi essence knowledge summary) basic knowledge of shell script programming
Ssh/scp does not prompt all activities are monitored and reported
2020.4.12 byte written test questions B DP D monotone stack
华为云服务器安装mysqlb for mysqld.service failed because the control process exited with error code.See “sys
由ASP.NET Core根据路径下载文件异常引发的探究
Maui学习之路(三)--Winui3深入探讨
基于 Nebula Graph 构建百亿关系知识图谱实践
智联招聘的基于 Nebula Graph 的推荐实践分享
愛可可AI前沿推介(7.2)
Tree binary search tree
手机app通达信添加自定义公式(分时T+0)为例子讲解
可视化技术在 Nebula Graph 中的应用
The task cannot be submitted after the installation of flick is completed
Introduction to database system Chapter 1 short answer questions - how was the final exam?
数仓中的维度表与事实表
Moveit obstacle avoidance path planning demo