Developed by Microsoft



Visual Studio

Introduction to development environment

Visual Studio is an integrated development environment (IDE) developed by Microsoft that supports multiple programming languages ​​such as C++, C#, VB.NET, Python, JavaScript, etc. Suitable for developing desktop applications, websites, cloud services and mobile applications.

Main functions

Version difference

Platform support

Visual Studio supports Windows operating systems, and Visual Studio for Mac is designed for macOS.

Common uses



Visual Studio syntax formatting

1. Automatically format code

Visual Studio provides shortcut keys to quickly format code, suitable for various programming languages: - Use the shortcut keys `Ctrl + K, Ctrl + D` to format the entire file. - Use the shortcut keys `Ctrl + K, Ctrl + F` to format the selected code block.

2. Enable automatic formatting

Visual Studio supports automatic code formatting when saving files: 1. Click **Tools > Options**. 2. Go to **Text Editor > [Language] > Coding Style > General**. 3. Check **Reformat code when file is saved**.

3. Modify formatting settings

1. Open **Tools > Options**. 2. Go to **Text Editor > [Language] > Coding Style > Formatting**. 3. Here you can adjust detailed formatting settings such as indentation, bracket style, and blank lines.

4. Use coding style profiles

Visual Studio supports coding style configuration files (.editorconfig) to unify the team's coding style: 1. Create a new `.editorconfig` file in the root directory of the project. 2. Define format rules, for example:
   [*.cs]
   indent_style = space
   indent_size = 4
   
3. After the file is saved, the formatting will automatically follow these rules.

5. Install extension tools

If the built-in formatting function does not meet your needs, you can install extension tools: - Search for and install tools in **Extension Manager**, such as **CodeMaid** or **ReSharper**. - These tools provide more code formatting and refactoring options.

6. Quickly correct format problems

When formatting problems arise, you can use quick fixes: - Right-click on the problematic code and select **Quick Actions and Refactoring**. - Select **Format File** or **Format Selection**.

7. Summary

- Use shortcut keys to quickly format code. - Enable automatic formatting when saving files. - Use `.editorconfig` to unify code style. - Install extension tools to improve formatting capabilities. - Make good use of the quick correction function to improve code readability.

.NET SDK version

Check installed .NET SDK

You can check the .NET SDK version installed on your computer via the command line tool:

dotnet --list-sdks

If a result similar to the following appears, it indicates the installed SDK version:

8.0.100 [C:\Program Files\dotnet\sdk]
9.0.100-preview.3.24172.9 [C:\Program Files\dotnet\sdk]

If the version you want to use does not appear, it means that it is not installed yet.

Download and install .NET SDK

  1. Go to.NET official download page
  2. Select the corresponding version (such as .NET 9) and operating system platform (Windows, macOS, Linux)
  3. Download and execute the installer

Turn on command prompt characters in Visual Studio

  1. Open Visual Studio
  2. Menu column click:Tools > Command Line > Developer Command Prompt Characters
  3. A command prompt window will open with the development environment path set, which can be used directly.dotnetOrder

If you don't see this option, you can also use the Windows Start menu to search for "Developer Command Prompt for VS" to open it.

Use Visual Studio’s built-in terminal (supported starting in 2022)

  1. In Visual Studio click:View > TerminalOr use shortcut keysCtrl + `
  2. Select terminal type (e.g. PowerShell or CMD)
  3. Can be entered directlydotnetCommand to check or operate SDK


C# language

language features

basic example

using System;

class Program {
    static void Main() {
        string name = "world";
        Console.WriteLine($"Hello, {name}!");
    }
}

Common application areas

Advanced functions



CS8618 Non-Nullable is not initialized

Warning content

CS8618 means: at the end of the constructor,Not Nullable's properties are not initialized, so the C# compiler warns that it might benull

Sample questions

public class Product {
    public string Name { get; set; } // Warning CS8618
}

Solution

Method 1: Assign value in constructor (recommended)

public class Product {
    public string Name { get; set; }

    public Product(string name) {
        Name = name;
    }
}

Method 2: Give default values ​​to attributes

public class Product {
    public string Name { get; set; } = string.Empty;
}

Method 3: Allow Null

public class Product {
    public string? Name { get; set; }
}

→ Applicable toNamereasonably allowed to benullsituation.

Method 4: UserequiredModifiers (supported by C# 11+)

public class Product {
    public required string Name { get; set; }
}

// The caller must be initialized
var p = new Product { Name = "Mobile phone" }; // OK

suggestion



.NET programs

Convert float to string to avoid scientific notation

Problem description

In C++/CLI, if you usefloatandSystem::StringAdd together, for example:

System::String^ tmpStr = "Value: " + someFloat;
whensomeFloatWhen very large or very small, it may be automatically displayed in scientific notation (e.g. 1.23E+05).

Solution

AvailableSystem::String::FormatorToStringUse a format string to specify the number of decimal places and avoid scientific notation.

Sample program

using namespace System;

float value = 123456.789f;

// Method 1: String::Format
String^ tmpStr1 = String::Format("Value: {0:F2}", value); // F2 represents 2 digits after the decimal point
Console::WriteLine(tmpStr1);

// Method 2: ToString matching format
String^ tmpStr2 = "Value: " + value.ToString("F2");
Console::WriteLine(tmpStr2);

//Method 3: More digits
String^ tmpStr3 = "Value: " + value.ToString("F6");
Console::WriteLine(tmpStr3);

Formatting code instructions



Get the latest file in a directory using .NET C++

Introduction

In .NET C++, you can useSystem::IONamespaces provide functions for manipulating files and directories. Obtaining the latest files in the directory can be achieved by reading all file information and comparing the last modification date.

Sample code

Here is a complete example showing how to get the latest file in a specified directory:

#include "stdafx.h"
#include <iostream>
#include <cliext/vector>
#include <System.IO>

using namespace System;
using namespace System::IO;
using namespace cliext;

int main()
{
    try
    {
        //Specify directory path
        String^ directoryPath = "C:\\Your\\Directory\\Path";

        // Check if the directory exists
        if (!Directory::Exists(directoryPath))
        {
            Console::WriteLine("Directory does not exist: {0}", directoryPath);
            return -1;
        }

        // Get all files in the directory
        array^ files = Directory::GetFiles(directoryPath);

        // If there are no files in the directory
        if (files->Length == 0)
        {
            Console::WriteLine("There is no file in the directory.");
            return 0;
        }

        // Find the latest file
        String^ newestFile = nullptr;
        DateTime newestTime = DateTime::MinValue;

        for each (String^ file in files)
        {
            // Get the last modification time of the file
            DateTime lastWriteTime = File::GetLastWriteTime(file);

            // Compare time and update latest file information
            if (lastWriteTime > newestTime)
            {
                newestTime = lastWriteTime;
                newestFile = file;
            }
        }

        // Output the latest file information
        Console::WriteLine("Latest file: {0}", newestFile);
        Console::WriteLine("Last modified time: {0}", newestTime);
    }
    catch (Exception^ ex)
    {
        Console::WriteLine("An error occurred: {0}", ex->Message);
    }

    return 0;
}

Code explanation

Application scenarios

Things to note



.NET: System.Reflection

1. What is System.Reflection?

System.ReflectionIt is a namespace in the .NET framework that provides tools for inspecting and manipulating metadata, allowing developers to dynamically inspect types, methods, properties, etc. at runtime, and dynamically create and manipulate objects.

2. Purpose of System.Reflection

3. Common System.Reflection categories

4. Usage examples

The following is a useSystem.ReflectionA sample program that shows how to dynamically check types and methods and call methods.

//Define a simple example class
public class SampleClass {
    public string SayHello(string name) {
        return $"Hello, {name}!";
    }
}

// Use Reflection to dynamically call methods
using System;
using System.Reflection;

class Program {
    static void Main() {
        //Create an instance of the SampleClass class
        Type sampleType = typeof(SampleClass);
        object sampleInstance = Activator.CreateInstance(sampleType);

        // Get SayHello method information
        MethodInfo methodInfo = sampleType.GetMethod("SayHello");

        // Dynamically call the SayHello method
        object result = methodInfo.Invoke(sampleInstance, new object[] { "World" });
        Console.WriteLine(result); // Output: Hello, World!
    }
}

In the above example, we useActivator.CreateInstanceto create an instance of the category and useMethodInfo.Invoketo call methodSayHello

5. Common application scenarios



System::Management::ManagementClass

use

System::Management::ManagementClassIs one of the classes in the .NET Framework that provides for working with Windows Management Instrumentation (WMI). It allows developers to read, manipulate and manage system information, such as hardware, operating system, network settings, etc.

namespace

System::Managementis locatedSystem.Management.dllIn the namespace, you need to add a reference before using this function.

Common uses

Simple example

// C++/CLI writing method
using namespace System;
using namespace System::Management;

int main() {
    try {
        ManagementClass^ mc = gcnew ManagementClass("Win32_OperatingSystem");
        for each (ManagementObject^ mo in mc->GetInstances()) {
            Console::WriteLine("OS Name: {0}", mo["Caption"]);
        }
    }
    catch (Exception^ ex) {
        Console::WriteLine("Error: {0}", ex->Message);
    }
    return 0;
}

Common errors and troubleshooting

Related categories



Fix Invalid class error in Win32_NetworkAdapterConfiguration

Error code description

Error code `0x80041010` occurs when using `System::Management::ManagementClass("Win32_NetworkAdapterConfiguration")`, indicating that WMI cannot find the class, which usually means:

Solution steps

Here is a complete fix to re-create the WMI repository for Windows 10/11:
net stop winmgmt
winmgmt /resetrepository
net start winmgmt

illustrate

Verify after repair

You can use any of the following methods to confirm whether the repair is successful:Method 1: PowerShell query
Get-WmiObject Win32_NetworkAdapterConfiguration
Method 2: WMI test tool (wbemtest)
  1. Press Win + R and enterwbemtest
  2. Click "Connect" and enterroot\cimv2and connect
  3. Click "Query" and enterSELECT * FROM Win32_NetworkAdapterConfiguration

Additional suggestions



How to execute .NET programs on Chromebook

1. Run .NET using Chromebook’s Linux support

Most modern Chromebooks support running Linux applications through the Crostini project.

  1. Enable Linux features:
  2. Install the .NET SDK:
  3. Compile and execute the .NET application in the terminal.

2. Use cloud development environment

You can use the cloud platform to run .NET programs on your Chromebook without installing any software locally.

3. Use Docker containers to run .NET

Chromebooks support the use of containers to run applications, and you can start a .NET environment through Docker.

  1. Install Docker in a Linux environment.
  2. Download the .NET container image:
    docker pull mcr.microsoft.com/dotnet/runtime:7.0
  3. Run your .NET program inside a container.

4. Use cross-platform support

Starting with .NET 6, applications can run across multiple platforms, including Linux. Compile your app into a cross-platform format and deploy to Chromebooks.

  1. Compile your application on any machine:
    dotnet publish -c Release -r linux-x64 --self-contained
  2. Transfer the compiled archive to your Chromebook and execute it using the included runtime.

Things to note



.NET UI Programming

Main technology

Simple WinForms example

using System;
using System.Windows.Forms;

public class MyForm : Form {
    public MyForm() {
        Button btn = new Button();
        btn.Text = "Click me";
        btn.Click += (s, e) => MessageBox.Show("You clicked the button!");
        Controls.Add(btn);
    }

    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.Run(new MyForm());
    }
}

Simple WPF example (XAML + C#)

// MainWindow.xaml
<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Title="WPF Example" Height="200" Width="300">
    <StackPanel>
        <Button Content="Click me" Click="Button_Click"/>
    </StackPanel>
</Window>

// MainWindow.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e) {
    MessageBox.Show("You clicked the button!");
}

Simple MAUI example

// MainPage.xaml
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             x:Class="MyApp.MainPage">
    <VerticalStackLayout Spacing="25" Padding="30">
        <Button Text="Click me" Clicked="OnButtonClicked"/>
    </VerticalStackLayout>
</ContentPage>

// MainPage.xaml.cs
private void OnButtonClicked(object sender, EventArgs e) {
    await DisplayAlert("Notification", "You clicked the button!", "OK");
}

UI technology selection advice

technology use platform
WinForms Rapidly develop desktop applications Windows
WPF Complex desktop applications, MVVM pattern Windows
MAUI Cross-platform application Windows、macOS、Android、iOS
Blazor Web front-end development Cross-platform (Web)


.NET traverses child controls to modify properties in batches

The following examples show how to useControls->GetEnumerator()Method to iterate through all child controls in a .NET form one by one and modify their properties in batches.

Sample code:

using System;
using System.Drawing;
using System.Windows.Forms;

public class FormExample : Form
{
    public FormExample()
    {
        //Initialize some controls
        Button button1 = new Button { Text = "Button 1", Location = new Point(10, 10) };
        TextBox textBox1 = new TextBox { Location = new Point(10, 50) };
        
        Controls.Add(button1);
        Controls.Add(textBox1);

        // Use GetEnumerator() to traverse and modify the control properties
        ModifyControls();
    }

    private void ModifyControls()
    {
        var enumerator = Controls.GetEnumerator();
        
        while (enumerator.MoveNext())
        {
            Control control = (Control)enumerator.Current;

            // Setting example: Set the background color of all controls to light blue
            control.BackColor = Color.LightBlue;
            
            // If the control item is a TextBox, make it non-editable
            if (control is TextBox)
            {
                control.Enabled = false;
            }
        }
    }
    
    //Start the application
    public static void Main()
    {
        Application.Run(new FormExample());
    }
}

illustrate

**GetEnumerator()**: Use the `Controls.GetEnumerator()` method to get the enumerator of the control item, so that all child controls can be traversed.

**Conditional modification**: In the `while` loop, modify the properties of each `Control` object, such as setting the background color to light blue, and make specific modifications based on the control type, such as setting the `TextBox` to non-editable.

**Use**: This method is very effective when you need to modify properties in batches, such as adjusting UI style or disabling multiple controls under specific circumstances.

Execution effect

After execution, the background color of all controls will change to light blue, and all `TextBox` controls will be set to non-editable.



Obtain the content of Message m in .NET StackTrace

Problem background

When the following error message appears in the stack trace, developers may need to checkMessageThe contents of the object:

   at ....MainForm.Dispose(Boolean A_0)
   at System.Windows.Forms.Form.WmClose(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   ...
    

At this time, it is necessary to overwrite or detectWndProcin methodMessage mto check its details.

Solution

Here are several ways to check or recordMessageThe contents of the object.

1. Override the WndProc method

If you have access to the source code of the form or control, it is recommended to overwriteWndProcmethod, directly record or checkMessage mcontent.

protected override void WndProc(ref Message m)
{
    try
    {
        //Record the content of Message
        Console.WriteLine($"Message Details: hWnd={m.HWnd}, Msg={m.Msg}, WParam={m.WParam}, LParam={m.LParam}");
        base.WndProc(ref m);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception: {ex}");
        throw; // Keep the original exception behavior
    }
}
    

This code will log relevant information each time a message is received and allow the developer to analyze it further.

2. Add exception handling to the Dispose method

If the error occurs inDisposeIn the method, you can add exception handling within the method to check relevant information.

protected override void Dispose(bool disposing)
{
    try
    {
        if (disposing)
        {
            // Release resources
        }
        base.Dispose(disposing);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception in Dispose: {ex}");
        throw;
    }
}
    

This ensures that important error information is not ignored when releasing resources.

3. Use global exception handling

If you cannot determine where the error occurred, you can use global exception handling to record stack traces and related information.


AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
    Exception ex = (Exception)args.ExceptionObject;
    Console.WriteLine($"Unhandled Exception: {ex}");
    Environment.Exit(1);
};

    

4. Use the Debug tool to check the Message

You can use Visual Studio to set breakpoints atWndProcorDisposemethod and checkMessageThe contents of the object.

Key properties of the Message object

Things to note



Overriding Form.WmClose(Message& m) in .NET C++

Problem background

In .NET C++/CLI,WmClose(Message& m)yesSystem.Windows.Forms.FormThe internal protection method cannot be directly overwritten. However, it is possible to overrideWndProcmethod to intercept and processWM_CLOSEmessage to achieve a similar overrideWmCloseeffect.

Complete example

#include <Windows.h>
#include <System.Windows.Forms.h>

using namespace System;
using namespace System::Windows::Forms;

public ref class CustomForm : public Form
{
protected:
    // Simulate override of WmClose behavior
    void WmClose(Message% m)
    {
        //Add custom WM_CLOSE behavior here
        if (MessageBox::Show("Are you sure you want to close the window?", "Confirm", MessageBoxButtons::YesNo) == DialogResult::Yes)
        {
            // Continue calling the base behavior for graceful shutdown
            this->Form::WndProc(m);
        }
        else
        {
            // Prevent window from closing
            return;
        }
    }

    // Override WndProc, intercept the WM_CLOSE message and call WmClose
    virtual void WndProc(Message% m) override
    {
        const int WM_CLOSE = 0x0010;

        if (m.Msg == WM_CLOSE)
        {
            WmClose(m); // Call the custom WmClose method
        }
        else
        {
            // Process other messages
            Form::WndProc(m);
        }
    }
};

[STAThread]
int main(array<String^>^ args)
{
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);

    CustomForm^ form = gcnew CustomForm();
    form->Text = "Override WmClose behavior example";
    Application::Run(form);

    return 0;
}
    

Code explanation

1. WmClose method

simulate overwriteWmCloseMethod to customize the window closing behavior here. Use a confirmation dialog box to ask the user if they want to close the window.

2. Override WndProc

overwriteWndProcmethod to interceptWM_CLOSEmessage and delegate it to a customWmClosemethod.

3. Continue to process other messages

without interceptionWM_CLOSEIn the case of calling the base classWndProcMethod to handle other messages.

Things to note



System::Windows::Forms::Control::InvokeRequired

Instructions for use

InvokeRequiredyesSystem::Windows::Forms::ControlThe attribute is used to determine whether the current execution thread is the UI execution thread to which the control item belongs. When accessing UI controls from a background thread, you should useInvokeMarshal the operation back to the UI thread.

Complete Example: Setting PictureBox Pictures

using namespace System;
using namespace System::Windows::Forms;
using namespace System::Drawing;

ref class ImageHelper {
public:
    static void SetImageSafe(PictureBox^ pPictureBox, Bitmap^ b) {
        if (pPictureBox == nullptr)
            return;

        if (pPictureBox->InvokeRequired) {
            // Use MethodInvoker to call the same function, but execute it in the UI thread
            pPictureBox->Invoke(
                gcnew MethodInvoker(gcnew Action(ImageHelper::InvokeCallback), 
                gcnew Tuple(pPictureBox, b))
            );
        } else {
            ApplyImage(pPictureBox, b);
        }
    }

private:
    // Marshaled function proxy
    static void InvokeCallback(Object^ state) {
        Tuple^ args = static_cast^>(state);
        ApplyImage(args->Item1, args->Item2);
    }

    // Actual execution of setting image logic
    static void ApplyImage(PictureBox^ pPictureBox, Bitmap^ b) {
        try {
            if (b != nullptr) {
                if (pPictureBox->Image != nullptr)
                    delete pPictureBox->Image;
                pPictureBox->Image = b;
            }
        }
        catch (System::Exception^ ex) {
            Console::WriteLine("Failed to set image: " + ex->Message);
        }
    }
};

Focus on sorting out



Protect pPictureBox->Image = b to avoid program crash

Possible causes of crash

Recommended practices for setting up images safely


using namespace System;
using namespace System::Windows::Forms;
using namespace System::Drawing;

void SetImageSafe(PictureBox^ pPictureBox, Bitmap^ b) {
    if (pPictureBox->InvokeRequired) {
        pPictureBox->Invoke(gcnew MethodInvoker(
            gcnew EventHandler(nullptr, &SetImageInvoker)
        ), gcnew array{ pPictureBox, b });
    } else {
        SetImageInternal(pPictureBox, b);
    }
}

void SetImageInvoker(Object^ sender, EventArgs^ e) {
    // If this version is not used, it can be ignored and retained as a complete reference.
}

void SetImageInternal(PictureBox^ pPictureBox, Bitmap^ b) {
    try {
        if (b != nullptr) {
            if (pPictureBox->Image != nullptr)
                delete pPictureBox->Image;

            pPictureBox->Image = b;
        }
    }
    catch (System::Exception^ ex) {
        Console::WriteLine("Failed to set image: " + ex->Message);
    }
}

Simplified version (anonymous delegation is recommended)

If you just want to quickly protect `pPictureBox->Image = b;`, the following writing method is more direct and effective:
using namespace System;
using namespace System::Windows::Forms;
using namespace System::Drawing;

void SafeAssignImage(PictureBox^ pPictureBox, Bitmap^ b) {
    if (pPictureBox->InvokeRequired) {
        pPictureBox->Invoke(gcnew MethodInvoker(gcnew delegate {
            try {
                if (b != nullptr) {
                    if (pPictureBox->Image != nullptr)
                        delete pPictureBox->Image;
                    pPictureBox->Image = b;
                }
            } catch (System::Exception^ ex) {
                Console::WriteLine("Failed to set image: " + ex->Message);
            }
        }));
    } else {
        try {
            if (b != nullptr) {
                if (pPictureBox->Image != nullptr)
                    delete pPictureBox->Image;
                pPictureBox->Image = b;
            }
        } catch (System::Exception^ ex) {
            Console::WriteLine("Failed to set image: " + ex->Message);
        }
    }
}

Additional information



Establish a unified language front-end development environment with Blazor

What is Blazor?

Blazor is a front-end framework launched by Microsoft that allows developers to use C# and Razor syntax to create interactive web applications. C# code can be executed in the browser without using JavaScript.

Developer benefits

Blazor mode

Integration with .NET

Blazor seamlessly integrates ASP.NET Core, can be combined with existing .NET applications, and supports dependency injection, routing, component architecture and other functions.

Deployment method

summary

For developers whose main technology is .NET, Blazor provides a solution corresponding to the unified JavaScript language of Node.js, allowing both the front and back ends to use C#, creating a more consistent development experience.



Build cross-platform applications using .NET MAUI

What is .NET MAUI?

.NET MAUI (Multi-platform App UI) is a cross-platform application framework launched by Microsoft. You can use C# and XAML to write once code and deploy it to Windows, Android, iOS and even macOS.

Developer benefits

Supported platforms

Blazor Hybrid Mode

Blazor Hybrid mode of .NET MAUI can be used to embed Web UI in native applications, allowing developers to use Razor components to develop cross-platform user interfaces while still accessing native APIs.

Integration and deployment

summary

.NET MAUI is currently the most complete .NET cross-platform solution. It can be combined with Blazor to achieve unified application development for web, desktop and mobile platforms, providing .NET developers with a full-end experience that is consistent in language and technology.



ASP.NET Core vs. .NET MAUI Comparison

position

Support platform

development language

UI and interaction

Applicable scenarios

Integration

.NET MAUI can be integrated with the back-end services created by ASP.NET Core through API calls to form a complete "front-end App + back-end API" architecture.

Summarize

ASP.NET Core solves the problems of "back-end services" and "Web applications", while .NET MAUI focuses on "client-side cross-platform apps". The two are not mutually exclusive, but are often used together to form a complete solution.



Simple .NET MAUI application example

Build a basic .NET MAUI application

Below is an example of a cross-platform application built using .NET MAUI that displays a button on the screen that updates the text count when clicked.

Main file: MainPage.xaml

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp.MainPage">

    <VerticalStackLayout Spacing="25" Padding="30">
        <Label x:Name="counterLabel"
               Text="You haven't clicked the button yet"
               FontSize="24"
               HorizontalOptions="Center" />

        <Button Text="Click me"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />
    </VerticalStackLayout>
</ContentPage>

Backend code: MainPage.xaml.cs

namespaceMauiApp;

public partial class MainPage : ContentPage
{
    int count = 0;

    public MainPage()
    {
        InitializeComponent();
    }

    private void OnCounterClicked(object sender, EventArgs e)
    {
        count++;
        counterLabel.Text = $"You have clicked {count} times";
    }
}

Execution method

summary

This simple example demonstrates the cross-platform capabilities of .NET MAUI. Developers only need to write XAML and C# code once to run it on multiple platforms at the same time.



Create a .NET MAUI project in Visual Studio

Step 1: Install necessary tools

Step 2: Create a new MAUI project

  1. Open Visual Studio
  2. Click "Create New Project"
  3. Search and select ".NET MAUI App"Template
  4. Click "Next" and enter the project name and location
  5. Click "Create" to complete project initialization

Step 3: Understand the project structure

Step 4: Execute the application

Additional information

summary

It only takes a few steps to create a .NET MAUI project using Visual Studio, and one set of code can be deployed to multiple platforms at the same time, making it an ideal choice for modern C# full-end developers.



MainPage.xaml examples and explanations

Example: MainPage.xaml

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyMauiApp.MainPage">

    <VerticalStackLayout Spacing="25" Padding="30"
                         VerticalOptions="Center">

        <Label
            Text="Welcome to .NET MAUI!"
            SemanticProperties.HeadingLevel="Level1"
            FontSize="32"
            HorizontalOptions="Center" />

        <Button
            x:Name="counterBtn"
            Text="Click me!"
            Clicked="OnCounterClicked"
            HorizontalOptions="Center" />

    </VerticalStackLayout>

</ContentPage>

Corresponding MainPage.xaml.cs

using System;
namespace MyMauiApp;

public partial class MainPage : ContentPage
{
    int count = 0;

    public MainPage()
    {
        InitializeComponent();
    }

    private void OnCounterClicked(object sender, EventArgs e)
    {
        count++;
        counterBtn.Text = $"You have clicked {count} times";
    }
}

Component Description

C# code description

Result effect

After execution, a welcome message and a button will be displayed in the center of the screen. Each time you click the button, the text on the button will update to "You have clicked X times."



MauiProgram.cs examples and explanations

Example: MauiProgram.cs

using Microsoft.Extensions.Logging;

namespace MyMauiApp;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        
        builder
            .UseMauiApp() //Specify the entry point of the application
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });

#if DEBUG
        builder.Logging.AddDebug();
#endif

        return builder.Build();
    }
}

Function description

Common extensions

Summarize

MauiProgram.csJust like ASP.NET Core'sStartup.csorProgram.cs, is the main setting center for application startup and service registration. When developing large MAUI applications, it is very common to extend this file to add DI, logging, component settings, etc.




email: [email protected]
T:0000
資訊與搜尋 | 回dev首頁
email: Yan Sa [email protected] Line: 阿央
電話: 02-27566655 ,03-5924828
阿央
泱泱科技
捷昱科技泱泱企業