### SplashScreen OnLoading Example
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Splashscreen.md
An example of overriding the OnLoading method in a SplashScreen to perform setup work and show progress.
```csharp
protected override async Task OnLoading()
{
//TODO: Do some actual work
for (int i = 0; i < 100; i+=5)
{
statusText.Text = $"Loading {i}%";
progressBar.Value = i;
await Task.Delay(50);
}
}
```
--------------------------------
### Maximize Window
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Maui.md
Example of how to maximize the MAUI window on Windows using WinUIEx.
```csharp
namespace MyApp.Maui;
#if WINDOWS
using WinUIEx;
#endif
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void OnMaximizeClicked(object sender, EventArgs e)
{
#if WINDOWS
var window = this.Window.Handler.PlatformView as Microsoft.UI.Xaml.Window;
window.Maximize(); // Use WinUIEx Extension method to maximize window
#endif
}
private void OnFullScreenClicked(object sender, EventArgs e)
{
#if WINDOWS
// Get the window manager
var manager = WinUIEx.WindowManager.Get(this.Window.Handler.PlatformView as Microsoft.UI.Xaml.Window);
if (manager.PresenterKind == Microsoft.UI.Windowing.AppWindowPresenterKind.Overlapped)
manager.PresenterKind = Microsoft.UI.Windowing.AppWindowPresenterKind.FullScreen;
else
manager.PresenterKind = Microsoft.UI.Windowing.AppWindowPresenterKind.Overlapped;
#endif
}
}
```
--------------------------------
### Get Window Manager Instance
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WindowManager.md
Demonstrates how to obtain an instance of the Window Manager for a given window.
```csharp
var manager = WinUIEx.WindowManager.Get(window);
```
--------------------------------
### NumberBox Usage Example
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/NumberBox.md
Example of how to use NumberBoxInt32 and NumberBoxDecimal controls in XAML, demonstrating various properties like Header, AllowNull, AcceptsExpression, Value binding, NumberFormatter, Description, and PlaceholderText.
```xml
```
--------------------------------
### Configure Window Manager Properties
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WindowManager.md
Shows examples of setting properties such as persistence ID, minimum dimensions, and backdrop for the Window Manager.
```csharp
manager.PersistenceId = "MainWindowPersistanceId";
manager.MinWidth = 640;
manager.MinHeight = 480;
manager.Backdrop = new WinUIEx.MicaSystemBackdrop();
```
--------------------------------
### Dispatcher to DispatcherQueue replacement
Source: https://github.com/dotmorten/winuiex/blob/main/docs/rules/WinUIEx1002.md
Example demonstrating how to replace Dispatcher.RunAsync with DispatcherQueue.TryEnqueue.
```cs
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
// your code
});
```
```cs
DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
{
// your code
});
```
--------------------------------
### Accessing Raw Assets at Runtime
Source: https://github.com/dotmorten/winuiex/blob/main/src/WinUIExMauiSample/Resources/Raw/AboutAssets.txt
Example of how to load and read the contents of a raw asset file at runtime using .NET MAUI Essentials.
```csharp
async Task LoadMauiAsset()
{
using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt");
using var reader = new StreamReader(stream);
var contents = reader.ReadToEnd();
}
```
--------------------------------
### Transparent Backdrop
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/CustomBackdrops.md
Example of setting a window's system backdrop to be fully transparent using TransparentTintBackdrop.
```xml
```
--------------------------------
### MauiAsset Build Action
Source: https://github.com/dotmorten/winuiex/blob/main/src/WinUIExMauiSample/Resources/Raw/AboutAssets.txt
Example of how to include raw assets in your .csproj file using the MauiAsset build action.
```xml
```
--------------------------------
### Fast Splash Screen with DISABLE_XAML_GENERATED_MAIN
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Splashscreen.md
Example of using SimpleSplashScreen with the DISABLE_XAML_GENERATED_MAIN preprocessor directive for faster initialization.
```csharp
#if DISABLE_XAML_GENERATED_MAIN
public static class Program
{
[System.STAThreadAttribute]
static void Main(string[] args)
{
// If you're using the WebAuthenticator, make sure you call this method first before the splashscreen shows
if (WebAuthenticator.CheckOAuthRedirectionActivation(true))
return;
var fss = SimpleSplashScreen.ShowDefaultSplashScreen();
WinRT.ComWrappersSupport.InitializeComWrappers();
Microsoft.UI.Xaml.Application.Start((p) => {
var context = new Microsoft.UI.Dispatching.DispatcherQueueSynchronizationContext(Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread());
System.Threading.SynchronizationContext.SetSynchronizationContext(context);
new App(fss); // Pass the splash screen to your app so it can close it on activation
});
}
}
#endif
```
--------------------------------
### Semi-transparent Blue Backdrop
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/CustomBackdrops.md
Example of creating a semi-transparent blue backdrop by specifying a TintColor for TransparentTintBackdrop.
```xml
```
--------------------------------
### Handle WM_SIZING Event
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WindowMessageMonitor.md
An example event handler that inspects raw Windows messages, specifically the WM_SIZING event, and logs details about the window's size change.
```csharp
struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
private void WindowMessageReceived(object sender, WindowMessageEventArgs e)
{
if (e.Message.MessageId == 0x0214) //WM_SIZING event
{
// https://docs.microsoft.com/en-us/windows/win32/winmsg/wm-sizing
string side = "";
switch (e.Message.WParam)
{
case 1: side = "Left"; break;
case 2: side = "Right"; break;
case 3: side = "Top"; break;
case 4: side = "Top-Left"; break;
case 5: side = "Top-Right"; break;
case 6: side = "Bottom"; break;
case 7: side = "Bottom-Left"; break;
case 8: side = "Bottom-Right"; break;
}
var rect = Marshal.PtrToStructure((IntPtr)e.Message.LParam);
System.Diagnostics.Debug.WriteLine($"WM_SIZING: Side: {side} Rect: {rect.left},{rect.top},{rect.right},{rect.bottom}");
}
}
```
--------------------------------
### Direct TrayIcon Class Usage
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/TrayIcon.md
Example of using the TrayIcon class directly for more fine-grained control, including creating a window-less application that can launch a window on demand.
```cs
public partial class App : Application
{
private TrayIcon icon;
private Window? _window;
public App()
{
InitializeComponent();
}
private Window GetMainWindow()
{
if (_window is not null)
return _window;
_window = new MainWindow();
_window.AppWindow.Closing += (s, e) =>
{
// Prevent closing so it can be re-activated later. We'll just hide it for now
// As an alternative don't cache the Window, but close and recreate a new Window every time.
e.Cancel = true;
s.Hide();
};
var wm = WindowManager.Get(_window);
wm.WindowStateChanged += (s, state) => wm.AppWindow.IsShownInSwitchers = state != WindowState.Minimized;
return _window;
}
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
// In OnLaunched we don't create a window but just the tray icon. We'll create a window later if we need to.
// Note: This icon will keep the application process alive as well.
icon = new TrayIcon(1, "Images/StatusOK.ico", "Test");
icon.IsVisible = true;
icon.Selected += (s, e) => GetMainWindow().Activate();
icon.ContextMenu += (w, e) =>
{
var flyout = new MenuFlyout();
flyout.Items.Add(new MenuFlyoutItem() { Text = "Open" });
((MenuFlyoutItem)flyout.Items[0]).Click += (s, e) => GetMainWindow().Activate();
flyout.Items.Add(new MenuFlyoutItem() { Text = "Quit App" });
((MenuFlyoutItem)flyout.Items[1]).Click += (s, e) =>
{
// Make sure we close both the main window, and the icon for the process to exit
_window?.Close();
icon.Dispose();
};
e.Flyout = flyout;
};
}
}
```
--------------------------------
### Custom NumberBoxFloat Implementation
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/NumberBox.md
Example of creating a custom NumberBox control for the 'float' type by subclassing NumberBox.
```cs
public class NumberBoxFloat : NumberBox
{
public NumberBoxFloat() => DefaultStyleKey = typeof(NumberBoxFloat);
}
```
--------------------------------
### Minimize-To-Tray and Launch-To-Tray Implementation
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/TrayIcon.md
Illustrates how to implement minimize-to-tray functionality by managing window visibility in switchers and how to launch the application directly into the tray.
```cs
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
_window = new MainWindow();
var wm = WindowManager.Get(_window);
wm.IsVisibleInTray = true; // Show app in tray
// Minimize to tray:
wm.WindowStateChanged += (s, state) =>
wm.AppWindow.IsShownInSwitchers = state != WindowState.Minimized;
if (MyAppSettings.LaunchToTray) // Delay activating the window by starting minimized
wm.WindowState = WindowState.Minimized;
else
_window.Activate();
}
```
--------------------------------
### OAuth startup activation check
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WebAuthenticator.md
Add an OAuth startup activation check in your application constructor or in the Main program.
```cs
public App()
{
if (WebAuthenticator.CheckOAuthRedirectionActivation())
return;
this.InitializeComponent();
}
```
--------------------------------
### SimpleSplashScreen Usage in App.xaml.cs
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Splashscreen.md
Demonstrates how to initialize and show a SimpleSplashScreen in the App.xaml.cs file.
```csharp
private SimpleSplashScreen fss { get; set; }
public App()
{
fss = SimpleSplashScreen.ShowDefaultSplashScreen(); // Shows the splash screen you already defined in your app manifest. For unpackaged apps use .ShowSplashScreenImage(imagepath):
// fss = SimpleSplashScreen.ShowSplashScreenImage(full_path_to_image_); // Shows a custom splash screen image. Must be a full-path (no relative paths)
this.InitializeComponent();
}
```
--------------------------------
### Inheriting from WindowEx
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WindowEx.md
Demonstrates how to change the base class of a window from `Window` to `WinUIEx.WindowEx` in both C# and XAML.
```csharp
public sealed partial class MainWindow : WinUIEx.WindowEx
```
```xml
```
--------------------------------
### Configure lifecycle events for window creation with WinUIEx
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Maui.md
Use `ConfigureLifecycleEvents` to hook into window creation events and apply WinUIEx extensions for window management, such as centering, persistence, and minimum size.
```csharp
using Microsoft.Maui.LifecycleEvents;
#if WINDOWS
using WinUIEx;
#endif
namespace MyApp.Maui
{
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
#if WINDOWS
builder.ConfigureLifecycleEvents(events =>
{
events.AddWindows(wndLifeCycleBuilder =>
{
wndLifeCycleBuilder.OnWindowCreated(window =>
{
window.CenterOnScreen(1024,768); //Set size and center on screen using WinUIEx extension method
var manager = WinUIEx.WindowManager.Get(window);
manager.PersistenceId = "MainWindowPersistanceId"; // Remember window position and size across runs
manager.MinWidth = 640;
manager.MinHeight = 480;
});
});
});
#endif
return builder.Build();
}
}
}
```
--------------------------------
### Include WinUIEx package in Windows target
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Maui.md
Add WinUIEx to the Windows build target by adding a package reference in the .csproj file.
```xml
```
--------------------------------
### App.xaml.cs OnLaunched Modification for SplashScreen
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Splashscreen.md
Demonstrates how to modify the OnLaunched method in App.xaml.cs to use the SplashScreen.
```csharp
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
var splash = new SplashScreen(typeof(MainWindow));
splash.Completed += (s, e) => m_window = e;
}
```
--------------------------------
### Register for protocol activation (Unpackaged Apps)
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WebAuthenticator.md
Register the application for protocol activation for unpackaged apps.
```cs
try
{
Microsoft.Windows.AppLifecycle.ActivationRegistrationManager.RegisterForProtocolActivation("myscheme", "Assets\\Square150x150Logo.scale-100", "My App Name", null);
var result = await WebAuthenticator.AuthenticateAsync(authorizeUri, callbackUri, cancellationToken);
}
finally
{
Microsoft.Windows.AppLifecycle.ActivationRegistrationManager.UnregisterForProtocolActivation("myscheme", null);
}
```
--------------------------------
### Move and resize window
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WindowExtensions.md
Offers methods for centering, resizing, and repositioning the window on the screen.
```cs
myWindow.CenterOnScreen();
myWindow.SetWindowSize(1024, 768);
myWindow.MoveAndResize(100, 100, 1024, 768);
```
--------------------------------
### Explicitly reference Windows App SDK package
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Maui.md
To address version conflicts between WinUIEx and the Windows App SDK, explicitly reference the Windows App SDK package with the version mentioned in the error.
```xml
```
--------------------------------
### Basic Tray Icon Visibility
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/TrayIcon.md
Demonstrates how to make the application's window visible in the Windows Tray by setting the IsVisibleInTray property.
```cs
var wm = WindowManager.Get(MyWindow);
wm.IsVisibleInTray = true;
```
--------------------------------
### Perform OAuth request using WinUIEx WebAuthenticator on Windows
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Maui.md
Conditionally use WinUIEx's WebAuthenticator for OAuth requests on Windows, falling back to .NET MAUI's WebAuthenticator on other platforms.
```csharp
#if WINDOWS
var result = await WinUIEx.WebAuthenticator.AuthenticateAsync(new Uri(authUri), new Uri(redirectUri));
#else
var result = await WebAuthenticator.AuthenticateAsync(new Uri(authUri), new Uri(redirectUri));
#endif
```
--------------------------------
### Bring window to the top
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WindowExtensions.md
Brings the specified window to the foreground, making it the active window.
```cs
myWindow.BringToFront();
```
--------------------------------
### Authenticate using default browser
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WebAuthenticator.md
Make a call to authenticate using your default browser.
```cs
WebAuthenticatorResult result = await WinUIEx.WebAuthenticator.AuthenticateAsync(authorizeUrl, callbackUri);
```
--------------------------------
### Hiding SimpleSplashScreen on Window Activation
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Splashscreen.md
Shows how to hide the SimpleSplashScreen once the main window is activated.
```csharp
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
m_window = new MainWindow();
m_window.Activate();
Window_Activated += Window_Activated;
}
private void Window_Activated(object sender, WindowActivatedEventArgs args)
{
((Window)sender).Activated -= Window_Activated;
fss?.Hide();
fss = null;
}
```
--------------------------------
### Use WinUIEx's WebAuthenticator in App.xaml.cs
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Maui.md
In `Platforms\Windows\App.xaml.cs`, add `WinUIEx.WebAuthenticator.CheckOAuthRedirectionActivation` to the App constructor to handle OAuth redirection on Windows.
```csharp
public App()
{
if (WinUIEx.WebAuthenticator.CheckOAuthRedirectionActivation())
return;
this.InitializeComponent();
}
```
--------------------------------
### Minimize/Maximize/Restore and Hide window
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WindowExtensions.md
Provides methods to control the basic visibility and state of a window.
```cs
myWindow.Minimize();
myWindow.Maximize();
myWindow.Restore();
myWindow.Hide();
```
--------------------------------
### Basic MediaPlayerElement Usage
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/MediaPlayer.md
This snippet demonstrates the basic usage of the MediaPlayerElement control, setting the video source and enabling transport controls.
```xml
```
--------------------------------
### Initialize WindowMessageMonitor
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WindowMessageMonitor.md
Initializes the WindowMessageMonitor and subscribes to the WindowMessageReceived event.
```csharp
var monitor = new WindowMessageMonitor(this);
monitor.WindowMessageReceived += OnWindowMessageReceived;
```
--------------------------------
### Custom Tray Icon Context Menu
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/TrayIcon.md
Shows how to add a custom context menu to the tray icon by subscribing to the TrayIconContextMenu event and providing a MenuFlyout.
```cs
wm.TrayIconContextMenu += (w, e) =>
{
var flyout = new MenuFlyout();
flyout.Items.Add(new MenuFlyoutItem() { Text = "Open" });
flyout.Items.Add(new MenuFlyoutItem() { Text = "Quit App" });
((MenuFlyoutItem)flyout.Items[0]).Click += (s, e) => MyWindow.Activate();
((MenuFlyoutItem)flyout.Items[1]).Click += (s, e) => MyWindow.Close();
e.Flyout = flyout;
};
```
--------------------------------
### SplashScreen Code-Behind Change
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Splashscreen.md
Shows the necessary code-behind modifications for a SplashScreen, changing the base class and constructor.
```csharp
public sealed partial class SplashScreen : WinUIEx.SplashScreen
{
public SplashScreen(Type window) : base(window)
{
this.InitializeComponent();
}
}
```
--------------------------------
### SplashScreen XAML Base Class Change
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/Splashscreen.md
Illustrates changing the base class of a Window from 'Window' to 'winuiex:SplashScreen' in XAML.
```xml
```
--------------------------------
### Blurred Composition-Brush Backdrop
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/CustomBackdrops.md
C# code for a blurred backdrop using CompositionBrushBackdrop and CreateHostBackdropBrush.
```csharp
public class BlurredBackdrop : CompositionBrushBackdrop
{
protected override Windows.UI.Composition.CompositionBrush CreateBrush(Windows.UI.Composition.Compositor compositor)
=> compositor.CreateHostBackdropBrush();
}
```
--------------------------------
### Correct Navigation Target
Source: https://github.com/dotmorten/winuiex/blob/main/docs/rules/WinUIEx1003.md
This code snippet shows the correct usage of Frame.Navigate by providing a target type that inherits from Page.
```csharp
frame.Navigate(typeof(MyPage));
```
--------------------------------
### Configuring Media Transport Controls
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/MediaPlayer.md
This snippet shows how to configure specific transport controls for the MediaPlayerElement, such as hiding the full window button.
```xml
```
--------------------------------
### Custom Animated Composition-Brush Backdrop
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/CustomBackdrops.md
C# code for a custom backdrop that animates its color using CompositionBrushBackdrop.
```csharp
public class ColorAnimatedBackdrop : CompositionBrushBackdrop
{
protected override Windows.UI.Composition.CompositionBrush CreateBrush(Windows.UI.Composition.Compositor compositor)
{
var brush = compositor.CreateColorBrush(Windows.UI.Color.FromArgb(255,255,0,0));
var animation = compositor.CreateColorKeyFrameAnimation();
var easing = compositor.CreateLinearEasingFunction();
animation.InsertKeyFrame(0, Colors.Red, easing);
animation.InsertKeyFrame (.333f, Colors.Green, easing);
animation.InsertKeyFrame (.667f, Colors.Blue, easing);
animation.InsertKeyFrame (1, Colors.Red, easing);
animation.InterpolationColorSpace = Windows.UI.Composition.CompositionColorSpace.Hsl;
animation.Duration = TimeSpan.FromSeconds(15);
animation.IterationBehavior = Windows.UI.Composition.AnimationIterationBehavior.Forever;
brush.StartAnimation("Color", animation);
return brush;
}
}
```
--------------------------------
### Incorrect Navigation Target
Source: https://github.com/dotmorten/winuiex/blob/main/docs/rules/WinUIEx1003.md
This code snippet demonstrates an incorrect usage of Frame.Navigate where the target type does not inherit from Page, which will trigger the analyzer.
```csharp
frame.Navigate(typeof(MyViewModel));
```
--------------------------------
### Make Window always-on-top
Source: https://github.com/dotmorten/winuiex/blob/main/docs/concepts/WindowExtensions.md
Enables or disables the always-on-top behavior for a window.
```cs
myWindow.SetIsAlwaysOnTop(true);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.