### Quick start Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/npm-usage A quick start example demonstrating how to initialize a project, generate a development certificate, and package the application using the `@microsoft/winappcli` functions. ```typescript import { init, packageApp, certGenerate } from '@microsoft/winappcli'; // Initialize a new project with defaults await init({ useDefaults: true }); // Generate a dev certificate await certGenerate({ install: true }); // Package the built app await packageApp({ inputFolder: './dist', cert: './devcert.pfx' }); ``` -------------------------------- ### Install SDKs After Initial Setup Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/usage Re-runs the initialization process to install or update SDKs while preserving existing project files. Use 'stable', 'preview', or 'experimental' for different SDK versions. ```bash # Re-run init to install SDKs - preserves existing files (manifest, etc.) winapp init --use-defaults --setup-sdks stable ``` -------------------------------- ### Installing and Enabling IME Immediately Source: https://learn.microsoft.com/en-us/windows/apps/develop/input/input-method-editor-requirements Use InstallLayoutOrTip to add the IME to user-enabled input methods immediately after installation. The psz parameter requires a specific format including language ID and GUIDs. ```cpp InstallLayoutOrTip(":{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"); ``` -------------------------------- ### Install Foundry Local and run a model Source: https://learn.microsoft.com/en-us/windows/apps/how-tos/ai-build Installs Foundry Local via winget and starts a Phi-4-Mini model. The model will be accessible at http://localhost:5272/openai/v1. ```bash winget install Microsoft.AIFoundry.Local foundry model run phi-4-mini ``` -------------------------------- ### Run the Electron App Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/guides/electron-setup Start the newly created Electron application to verify the setup. This command will launch the default Electron Forge window. ```bash npm start ``` -------------------------------- ### Download and Install All Store Package Updates Source: https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/package-updates-from-store This C# code demonstrates how to get available app and optional store package updates, download them, and then install them. It includes logic to handle potential errors during the download and installation process, specifically for mandatory updates. ```csharp private StoreContext context = null; // Downloads and installs package updates in separate steps. public async Task DownloadAndInstallAllUpdatesAsync() { if (context == null) { context = StoreContext.GetDefault(); } // Get the updates that are available. IReadOnlyList updates = await context.GetAppAndOptionalStorePackageUpdatesAsync(); if (updates.Count != 0) { // Download the packages. bool downloaded = await DownloadPackageUpdatesAsync(updates); if (downloaded) { // Install the packages. await InstallPackageUpdatesAsync(updates); } } } // Helper method for downloading package updates. private async Task DownloadPackageUpdatesAsync(IEnumerable updates) { bool downloadedSuccessfully = false; IAsyncOperationWithProgress downloadOperation = this.context.RequestDownloadStorePackageUpdatesAsync(updates); // The Progress async method is called one time for each step in the download process for each // package in this request. downloadOperation.Progress = async (asyncInfo, progress) => { await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { downloadProgressBar.Value = progress.PackageDownloadProgress; }); }; StorePackageUpdateResult result = await downloadOperation.AsTask(); switch (result.OverallState) { case StorePackageUpdateState.Completed: downloadedSuccessfully = true; break; default: // Get the failed updates. var failedUpdates = result.StorePackageUpdateStatuses.Where( status => status.PackageUpdateState != StorePackageUpdateState.Completed); // See if any failed updates were mandatory if (updates.Any(u => u.Mandatory && failedUpdates.Any( failed => failed.PackageFamilyName == u.Package.Id.FamilyName))) { // At least one of the updates is mandatory. Perform whatever actions you // want to take for your app: for example, notify the user and disable // features in your app. HandleMandatoryPackageError(); } break; } return downloadedSuccessfully; } // Helper method for installing package updates. private async Task InstallPackageUpdatesAsync(IEnumerable updates) { IAsyncOperationWithProgress installOperation = this.context.RequestDownloadAndInstallStorePackageUpdatesAsync(updates); // The package updates were already downloaded separately, so this method skips the download // operation and only installs the updates; no download progress notifications are provided. StorePackageUpdateResult result = await installOperation.AsTask(); switch (result.OverallState) { case StorePackageUpdateState.Completed: break; default: // Get the failed updates. var failedUpdates = result.StorePackageUpdateStatuses.Where( status => status.PackageUpdateState != StorePackageUpdateState.Completed); // See if any failed updates were mandatory if (updates.Any(u => u.Mandatory && failedUpdates.Any(failed => failed.PackageFamilyName == u.Package.Id.FamilyName))) { // At least one of the updates is mandatory, so tell the user. HandleMandatoryPackageError(); } break; } } // Helper method for handling the scenario where a mandatory package update fails to // download or install. Add code to this method to perform whatever actions you want // to take, such as notifying the user and disabling features in your app. private void HandleMandatoryPackageError() { } ``` -------------------------------- ### Run npm Install to Trigger Setup Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/guides/electron-setup Execute this command to trigger the postinstall script, which configures the Windows environment for your Electron app. ```bash npm install ``` -------------------------------- ### App.cpp Setup for Composition Interop Source: https://learn.microsoft.com/en-us/windows/apps/develop/composition/composition-native-interop Set up the App.cpp file for composition interop, including necessary namespaces and ABI definitions. This example demonstrates rendering text using DirectWrite and Direct2D within a composition surface. ```cpp // NOTE: This example uses UWP-specific APIs. For WinUI, replace CoreWindow with your app's Window handle. // App.cpp //********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //********************************************************* #include "pch.h" using namespace winrt; using namespace winrt::Windows::ApplicationModel::Core; using namespace winrt::Windows::Foundation; using namespace winrt::Windows::Foundation::Numerics; using namespace winrt::Windows::Graphics::DirectX; using namespace winrt::Windows::Graphics::DirectX::Direct3D11; using namespace winrt::Windows::UI; using namespace winrt::Microsoft::UI::Composition; using namespace winrt::Windows::UI::Core; namespace abi { using namespace ABI::Windows::Foundation; using namespace ABI::Windows::Graphics::DirectX; using namespace ABI::Microsoft::UI::Composition; } // An app-provided helper to render lines of text. struct SampleText { SampleText(winrt::com_ptr<::IDWriteTextLayout> const& text, CompositionGraphicsDevice const& compositionGraphicsDevice) : m_text(text), m_compositionGraphicsDevice(compositionGraphicsDevice) { // Create the surface just big enough to hold the formatted text block. DWRITE_TEXT_METRICS metrics; winrt::check_hresult(m_text->GetMetrics(&metrics)); winrt::Windows::Foundation::Size surfaceSize{ metrics.width, metrics.height }; CompositionDrawingSurface drawingSurface{ m_compositionGraphicsDevice.CreateDrawingSurface( surfaceSize, DirectXPixelFormat::B8G8R8A8UIntNormalized, DirectXAlphaMode::Premultiplied) }; ``` -------------------------------- ### Initialize and read light sensor data in C# Source: https://learn.microsoft.com/en-us/windows/apps/develop/devices-sensors/use-the-light-sensor This snippet shows the complete setup for a light sensor, including getting the default sensor, setting the report interval, and handling the ReadingChanged event to display lux values. It also includes error handling if no light sensor is found. ```C# using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml.Controls; using Windows.Devices.Sensors; amespace DevicesDemo.Pages { public sealed partial class LightSensorPage : Page { private LightSensor? lightSensor; public LightSensorPage() { InitializeComponent(); // Get the default light sensor object. lightSensor = LightSensor.GetDefault(); if (lightSensor != null) { // Establish the report interval. uint minReportInterval = lightSensor.MinimumReportInterval; uint reportInterval = minReportInterval > 16 ? minReportInterval : 16; lightSensor.ReportInterval = reportInterval; // Assign an event handler for the reading-changed event. lightSensor.ReadingChanged += LightSensor_ReadingChanged; } else { statusBar.Message = "No light sensor was found."; statusBar.Severity = InfoBarSeverity.Error; statusBar.IsOpen = true; } } // This event handler writes the current light // reading to the text block on the XAML page. private void LightSensor_ReadingChanged(LightSensor sender, LightSensorReadingChangedEventArgs args) { DispatcherQueue?.TryEnqueue(DispatcherQueuePriority.Normal, () => { LightSensorReading reading = args.Reading; txtLuxValue.Text = String.Format("{0,5:0.00}", reading.IlluminanceInLux); }); } } } ``` ```XAML ``` -------------------------------- ### Get app install directory (C#) Source: https://learn.microsoft.com/en-us/windows/apps/develop/files/file-access-permissions Retrieve a StorageFolder representing the app's install directory. This location is read-only. ```csharp Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation; ``` -------------------------------- ### Get app install directory (C++/WinRT) Source: https://learn.microsoft.com/en-us/windows/apps/develop/files/file-access-permissions Retrieve a StorageFolder representing the app's install directory using C++/WinRT. This location is read-only. ```cpp #include ... Windows::Storage::StorageFolder installedLocation{ Windows::ApplicationModel::Package::Current().InstalledLocation() }; ``` -------------------------------- ### WPF Project File Example Source: https://learn.microsoft.com/en-us/windows/apps/develop/ai-assisted/migrate/wpf-to-winui Shows the before and after project file configurations for migrating from WPF to WinUI 3. ```XML net10.0-windows true net10.0-windows10.0.19041.0 10.0.19041.31 ``` -------------------------------- ### Initialize UWP App for Microsoft Store Source: https://learn.microsoft.com/en-us/windows/apps/publish/msstore-dev-cli/commands Use the `init` command to set up your UWP application for publishing to the Microsoft Store. Provide the local path to your project. ```bash msstore init "C:\path\to\uwp_app" ``` -------------------------------- ### Starting Animation on Effect Property Source: https://learn.microsoft.com/en-us/windows/apps/develop/composition/composition-effects Starts an animation on a specific property of an effect instance. This example applies the previously defined ScalarKeyFrameAnimation to the 'saturationEffect.Saturation' property. ```csharp catEffect.Properties.StartAnimation("saturationEffect.Saturation", effectAnimation); ``` -------------------------------- ### Initialize .NET MAUI App for Microsoft Store Source: https://learn.microsoft.com/en-us/windows/apps/publish/msstore-dev-cli/commands Use the `init` command to set up your .NET MAUI application for publishing to the Microsoft Store. Provide the local path to your project. ```bash msstore init "C:\path\to\maui_app" ``` -------------------------------- ### Get file from app install directory (C#) Source: https://learn.microsoft.com/en-us/windows/apps/develop/files/file-access-permissions Retrieve a StorageFile directly from the app's install directory using an app URI. The "ms-appx:///" prefix indicates the install directory. This location is read-only. ```csharp using Windows.Storage; StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///file.txt")); ``` -------------------------------- ### Quick Start: Initialize, Generate Cert, and Package App Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/npm-usage Demonstrates initializing a new project, generating a development certificate, and packaging an application using the @microsoft/winappcli programmatic API. ```typescript import { init, packageApp, certGenerate } from '@microsoft/winappcli'; // Initialize a new project with defaults await init({ useDefaults: true }); // Generate a dev certificate await certGenerate({ install: true }); // Package the built app await packageApp({ inputFolder: './dist', cert: './devcert.pfx' }); ``` -------------------------------- ### Basic InteractionTracker Setup Source: https://learn.microsoft.com/en-us/windows/apps/develop/composition/interaction-tracker-manipulations Demonstrates the initial setup for InteractionTracker, including creating the tracker, setting its position bounds, configuring a VisualInteractionSource, and adding the source to the tracker. This covers steps 1-5 of the InteractionTracker setup process. ```csharp private void InteractionTrackerSetup(Compositor compositor, Visual hitTestRoot) { // #1 Create InteractionTracker object var tracker = InteractionTracker.Create(compositor); // #2 Set Min and Max positions tracker.MinPosition = new Vector3(-1000f); tracker.MaxPosition = new Vector3(1000f); // #3 Setup the VisualInteractionSource var source = VisualInteractionSource.Create(hitTestRoot); // #4 Set the properties for the VisualInteractionSource source.ManipulationRedirectionMode = VisualInteractionSourceRedirectionMode.CapableTouchpadOnly; source.PositionXSourceMode = InteractionSourceMode.EnabledWithInertia; source.PositionYSourceMode = InteractionSourceMode.EnabledWithInertia; // #5 Add the VisualInteractionSource to InteractionTracker tracker.InteractionSources.Add(source); } ``` -------------------------------- ### Get file from app install directory (C++/WinRT) Source: https://learn.microsoft.com/en-us/windows/apps/develop/files/file-access-permissions Retrieve a StorageFile directly from the app's install directory using an app URI with C++/WinRT. The "ms-appx:///" prefix indicates the install directory. This location is read-only. ```cpp Windows::Foundation::IAsyncAction ExampleCoroutineAsync() { Windows::Storage::StorageFile file{ co_await Windows::Storage::StorageFile::GetFileFromApplicationUriAsync(Windows::Foundation::Uri{L"ms-appx:///file.txt"}) }; // Process file } ``` -------------------------------- ### Initialize Electron App for Microsoft Store Source: https://learn.microsoft.com/en-us/windows/apps/publish/msstore-dev-cli/commands Use the `init` command to set up your Electron application for publishing to the Microsoft Store. Provide the local path to your project. For Electron projects, `Npm` and `Yarn` are supported. ```bash msstore init "C:\path\to\electron_app" ``` -------------------------------- ### Initialize Sample User Accounts Source: https://learn.microsoft.com/en-us/windows/apps/develop/security/windows-hello-auth-service This method populates a mock user database with a sample user account, including username and password. It's used to demonstrate migration to Windows Hello authentication. ```csharp namespace WindowsHelloLogin.AuthService { public class MockStore { private const string USER_ACCOUNT_LIST_FILE_NAME = "userAccountsList.txt"; // This cannot be a const because the LocalFolder is accessed at runtime private string _userAccountListPath = Path.Combine( ApplicationData.Current.LocalFolder.Path, USER_ACCOUNT_LIST_FILE_NAME); private List _mockDatabaseUserAccountsList; public MockStore() { _mockDatabaseUserAccountsList = new List(); _ = LoadAccountListAsync(); } private async Task InitializeSampleUserAccountsAsync() { // Create a sample Traditional User Account that only has a Username and Password // This will be used initially to demonstrate how to migrate to use Windows Hello var sampleUserAccount = new UserAccount() { UserId = Guid.NewGuid(), Username = "sampleUsername", Password = "samplePassword", }; // Add the sampleUserAccount to the _mockDatabase _mockDatabaseUserAccountsList.Add(sampleUserAccount); await SaveAccountListAsync(); } } } ``` -------------------------------- ### Example Startup Task Declaration in Package Manifest Source: https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/desktop-to-uwp-extensions This example demonstrates how to integrate the startup task extension within a complete application package manifest. It includes the necessary namespaces and application structure. ```XML ``` -------------------------------- ### Get Windows SDK Component Paths Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/usage Retrieve paths to installed Windows SDK components, including the .winapp workspace directory, package installation directories, and generated header locations. ```bash winapp get-winapp-path [options] ``` -------------------------------- ### Initialize WinUI 3 App for Microsoft Store Source: https://learn.microsoft.com/en-us/windows/apps/publish/msstore-dev-cli/commands Use the `init` command to set up your WinUI 3 application for publishing to the Microsoft Store. Provide the local path to your project. ```bash msstore init "C:\path\to\winui3_app" ``` -------------------------------- ### Create and Start a Spring Animation Programmatically Source: https://learn.microsoft.com/en-us/windows/apps/develop/composition/spring-animations Define a spring animation for UI element motion and start it when a button is clicked. This example toggles the expanded state of a navigation pane with a springy motion. ```C# private void Button_Clicked(object sender, RoutedEventArgs e) { _springAnimation = _compositor.CreateSpringScalarAnimation(); _springAnimation.DampingRatio = 0.75f; _springAnimation.Period = TimeSpan.FromSeconds(0.5); if (!_expanded) { _expanded = true; _propSet.InsertBoolean("expanded", true); _springAnimation.InitialValueExpression["FinalValue"] = "this.StartingValue + 250"; } else { _expanded = false; _propSet.InsertBoolean("expanded", false); _springAnimation.InitialValueExpression["FinalValue"] = "this.StartingValue - 250"; } _naviPane.StartAnimation("Offset.X", _springAnimation); } ``` -------------------------------- ### init() Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/npm-usage Starts the initialization process for a Windows app, setting up everything needed for development. This includes creating Package.appxmanifest, downloading SDKs, and generating projections. It can also create winapp.yaml for version management. ```APIDOC ## `init()` ### Description Starts the initialization process for a Windows app with required setup. Sets up everything needed for Windows app development: creates Package.appxmanifest with default assets, downloads Windows SDK and Windows App SDK packages, and generates projections. When SDK packages are managed (--setup-sdks stable/preview/experimental), also creates winapp.yaml to pin versions for 'restore'/'update'; with --setup-sdks none (e.g., for Rust/Tauri projects that bring their own SDK bindings), no winapp.yaml is created. Interactive by default (use --use-defaults to skip prompts). Use 'restore' instead if you cloned a repo that already has winapp.yaml. Use 'manifest generate' if you only need a manifest, or 'cert generate' if you need a development certificate for code signing. ### Method Signature ```typescript function init(options?: InitOptions): Promise ``` ### Parameters #### Options - **`baseDirectory`** (string | undefined) - Optional - Base/root directory for the winapp workspace, for consumption or installation. - **`configDir`** (string | undefined) - Optional - Directory to read/store configuration (default: current directory). - **`configOnly`** (boolean | undefined) - Optional - Only handle configuration file operations (create if missing, validate if exists). Skip package installation and other workspace setup steps. - **`ignoreConfig`** (boolean | undefined) - Optional - Don't use configuration file for version management. - **`noGitignore`** (boolean | undefined) - Optional - Don't update .gitignore file. - **`setupSdks`** (SdkInstallMode | undefined) - Optional - SDK installation mode: 'stable' (default), 'preview', 'experimental', or 'none' (skip SDK installation). - **`useDefaults`** (boolean | undefined) - Optional - Do not prompt, and use default of all prompts. _Also accepts CommonOptions (`quiet`, `verbose`, `cwd`)._ ``` -------------------------------- ### Create a Local Settings Container Source: https://learn.microsoft.com/en-us/windows/apps/develop/data/store-and-retrieve-app-data Creates a local settings container named 'exampleContainer' and adds a setting named 'exampleSetting'. The container is created if it doesn't already exist. ```C# Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; // Setting in a container Windows.Storage.ApplicationDataContainer container = localSettings.CreateContainer("exampleContainer", Windows.Storage.ApplicationDataCreateDisposition.Always); if (localSettings.Containers.ContainsKey("exampleContainer")) { localSettings.Containers["exampleContainer"].Values["exampleSetting"] = "Hello Windows"; } ``` -------------------------------- ### Get and Output Syndication Item Title Source: https://learn.microsoft.com/en-us/windows/apps/develop/cpp-winrt/get-started This example demonstrates how to get the title text of a syndication item as a winrt::hstring and output it to the console. The winrt::hstring is converted to a C-style string using .c_str() for output. ```cpp winrt::hstring titleAsHstring = syndicationItem.Title().Text(); // Omitted: there's a little bit of extra work here to remove the trademark symbol from the title text. std::wcout << titleAsHstring.c_str() << std::endl; ``` -------------------------------- ### Initialize WinRT Apartment and Setup WebView2 Source: https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/ui/apply-mica-win32 This snippet shows the initial setup within the `WinMain` function for a Win32 WebView2 application. It demonstrates how to initialize the WinRT apartment as single-threaded, enable referencing the Windows App SDK, register a window class, create a dispatcher queue controller, initialize a compositor, and create a WebView2 window. Use this for the entry point of your application when integrating Mica with WebView2. ```cpp int __stdcall WinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ PSTR, _In_ int) { winrt::init_apartment(winrt::apartment_type::single_threaded); // Enable referencing the WindowsAppSDK from an unpackaged app. // Remember to have a matching Microsoft.WindowsAppRuntime.Redist installed. // https://learn.microsoft.com/windows/apps/windows-app-sdk/deploy-unpackaged-apps Utilities::WindowsAppSDKBootstrapperContext sdkContext; CompositionWindow::RegisterWindowClass(); // A dispatcher queue is required to be able to create a compositor. auto controller = Utilities::CreateDispatcherQueueControllerForCurrentThread(); auto compositor = winrt::Compositor(); auto window = WebView2Window(compositor, L"Hello, WebView2!"); ... } ``` -------------------------------- ### Basic ListView Setup Source: https://learn.microsoft.com/en-us/windows/apps/develop/ui/controls/item-containers-templates An empty ListView declaration. This serves as a starting point before applying templates or data binding. ```xaml ``` -------------------------------- ### Full Dark Mode Detection Example Source: https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/ui/apply-windows-themes A complete C++ example demonstrating how to initialize the WinRT apartment, detect Dark mode at startup, and track changes using event handlers. Includes a loop to keep the application running. ```cpp inline bool IsColorLight(Windows::UI::Color& clr) { return (((5 * clr.G) + (2 * clr.R) + clr.B) > (8 * 128)); } int main() { init_apartment(); auto settings = UISettings(); auto foreground = settings.GetColorValue(UIColorType::Foreground); bool isDarkMode = static_cast(IsColorLight(foreground)); wprintf(L"\nisDarkMode: %u\n", isDarkMode); auto revoker = settings.ColorValuesChanged([settings](auto const& /*sender*/, auto const& /*args*/) { auto foregroundRevoker = settings.GetColorValue(UIColorType::Foreground); bool isDarkModeRevoker = static_cast(IsColorLight(foregroundRevoker)); wprintf(L"isDarkModeRevoker: %d\n", isDarkModeRevoker); }); static bool s_go = true; while (s_go) { Sleep(50); } } ``` -------------------------------- ### Sample Response for Get Current Draft Packages API Source: https://learn.microsoft.com/en-us/windows/apps/publish/store-submission-api This JSON structure illustrates the response from the 'Get Current Draft Packages API', detailing package information, including IDs, URLs, languages, architectures, and installation parameters. ```json { "isSuccess": true, "errors": [{ "code": "badrequest", "message": "Error Message 1", "target": "listings" }, { "code": "warning", "message": "Warning Message 1", "target": "properties" }], "responseData":{ "packages":[{ "packageId": "pack0832", "packageUrl": "https://www.contoso.com/downloads/1.1/setup.exe", "languages": ["en-us"], "architectures": ["X86"], "isSilentInstall": true, "installerParameters": "/s", "genericDocUrl": "https://docs.contoso.com/doclink", "errorDetails": [{ "errorScenario": "rebootRequired", "errorScenarioDetails": [{ "errorValue": "ERR001001", "errorUrl": "https://errors.contoso.com/errors/ERR001001" }] }], "packageType": "exe" }] } } ``` -------------------------------- ### Initialize Project with WinApp CLI Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/guides/electron-setup Initializes a new project for Windows development using the `winapp init` command. This command sets up the app manifest, assets, and SDKs. Follow the prompts to configure package name, publisher, version, entry point, and SDKs. ```bash npx winapp init . ``` -------------------------------- ### Get AppWindow and Customize Title Bar in C# Source: https://learn.microsoft.com/en-us/windows/apps/develop/title-bar This example demonstrates how to obtain the `AppWindow` and its `TitleBar` object to set `ExtendsContentIntoTitleBar` to `true`. This approach is necessary for apps not using WinUI 1.3 or later, as it uses interop APIs to get the `AppWindow`. ```csharp using Microsoft.UI; using Microsoft.UI.Windowing; using WinRT.Interop; private AppWindow m_AppWindow; public MainWindow() { this.InitializeComponent(); m_AppWindow = GetAppWindowForCurrentWindow(); var titleBar = m_AppWindow.TitleBar; // Hide system title bar. titleBar.ExtendsContentIntoTitleBar = true; } private AppWindow GetAppWindowForCurrentWindow() { IntPtr hWnd = WindowNative.GetWindowHandle(this); WindowId wndId = Win32Interop.GetWindowIdFromWindow(hWnd); return AppWindow.GetFromWindowId(wndId); } ``` -------------------------------- ### Initialize WinRT and Setup for Mica in Win32 App Source: https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/ui/apply-mica-win32 This snippet shows the initial setup within WinMain for an unpackaged Win32 application to use Mica. It includes initializing WinRT, setting up the Windows App SDK context, registering the window class, creating a dispatcher queue controller, and initializing a WinRT compositor. ```cpp int __stdcall WinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ PSTR, _In_ int) { // Initialize WinRt Instance winrt::init_apartment(); // Enable referencing the WindowsAppSDK from an unpackaged app. Utilities::WindowsAppSDKBootstrapperContext sdkContext; // Register Window class before making the window. MicaWindow::RegisterWindowClass(); // Mica requires a compositor, which also requires a dispatcher queue. auto controller = Utilities::CreateDispatcherQueueControllerForCurrentThread(); auto compositor = winrt::Compositor(); // Create your window... ... } ``` -------------------------------- ### Get top-level file properties Source: https://learn.microsoft.com/en-us/windows/apps/develop/files/file-properties This example enumerates all of the files in the Pictures library and accesses a few of each file's top-level properties such as name and type. ```APIDOC ## Get top-level file properties ### Description Accesses top-level file properties like name and type for files within a specified library. ### Method This is a conceptual example demonstrating property access, not a direct API call. ### Endpoint N/A ### Parameters N/A ### Request Example ```csharp // Enumerate all files in the Pictures library. var folder = Windows.Storage.KnownFolders.PicturesLibrary; var query = folder.CreateFileQuery(); var files = await query.GetFilesAsync(); foreach (Windows.Storage.StorageFile file in files) { StringBuilder fileProperties = new StringBuilder(); // Get top-level file properties. fileProperties.AppendLine("File name: " + file.Name); fileProperties.AppendLine("File type: " + file.FileType); } ``` ### Response #### Success Response Properties such as file name and file type are appended to a StringBuilder. #### Response Example ``` File name: example.jpg File type: .jpg ``` ``` -------------------------------- ### Initialize PWA for Microsoft Store Source: https://learn.microsoft.com/en-us/windows/apps/publish/msstore-dev-cli/commands Use the `init` command to set up your Progressive Web App (PWA) for publishing to the Microsoft Store. Provide the URL to your PWA and specify an output directory. ```bash msstore init https://contoso.com --output . ``` -------------------------------- ### Starting a Storyboard Animation in C++/WinRT Source: https://learn.microsoft.com/en-us/windows/apps/design/motion/storyboarded-animations This C++/WinRT code snippet demonstrates how to initiate a Storyboard animation, similar to the C# example but using WinRT syntax. ```C++/WinRT myStoryboard().Begin(); ``` -------------------------------- ### Initialize Core Window and DWrite Factory with C++/WinRT Source: https://learn.microsoft.com/en-us/windows/apps/develop/composition/composition-native-interop This snippet demonstrates initializing a Core Window, setting up the compositor, and creating a DWrite factory for text rendering. ```cpp CoreWindow window = CoreWindow::GetForCurrentThread(); window.Activate(); CoreDispatcher dispatcher = window.Dispatcher(); dispatcher.ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit); m_compositor = Compositor{}; m_target = m_compositor.CreateTargetForCurrentView(); ContainerVisual root = m_compositor.CreateContainerVisual(); m_target.Root(root); Initialize(); winrt::check_hresult( ::DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED, __uuidof(m_dWriteFactory), reinterpret_cast<::IUnknown**>(m_dWriteFactory.put()) ) ); winrt::check_hresult( m_dWriteFactory->CreateTextFormat( L"Segoe UI", nullptr, DWRITE_FONT_WEIGHT_REGULAR, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 36.f, L"en-US", m_textFormat.put() ) ); Rect windowBounds{ window.Bounds() }; std::wstring text{ L"Hello, World!" }; ``` -------------------------------- ### Initialize MultiSourceMediaFrameReader Source: https://learn.microsoft.com/en-us/windows/apps/develop/camera/process-media-frames-with-mediaframereader Create and initialize the MultiSourceMediaFrameReader, register the FrameArrived event handler, and start the reader. This setup is essential for processing frames from multiple sources. ```csharp m_multiFrameReader = await m_mediaCapture.CreateMultiSourceFrameReaderAsync( new[] { colorSource, depthSource }); m_multiFrameReader.FrameArrived += MultiFrameReader_FrameArrived; m_frameRenderer = new FrameRenderer(iFrameReaderImageControl); MultiSourceMediaFrameReaderStartStatus startStatus = await m_multiFrameReader.StartAsync(); if (startStatus != MultiSourceMediaFrameReaderStartStatus.Success) { throw new InvalidOperationException( "Unable to start reader: " + startStatus); } this.CorrelationFailed += MainWindow_CorrelationFailed; Task.Run(() => NotifyAboutCorrelationFailure(m_tokenSource.Token)); ``` -------------------------------- ### Install .NET Desktop Runtime on Windows Source: https://learn.microsoft.com/en-us/windows/apps/publish/msstore-dev-cli/commands-exe Installs the .NET 8 Desktop Runtime using winget, which is a prerequisite for the Microsoft Store Developer CLI on Windows. ```bash winget install Microsoft.DotNet.DesktopRuntime.8 ``` -------------------------------- ### Example: Integrate a fullTrustProcess extension in the package manifest Source: https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/desktop-to-uwp-extensions This example shows how to add the `windows.fullTrustProcess` extension to your UWP app's package manifest. Ensure the `runFullTrust` capability is declared. This setup allows your UWP app to launch and interact with a Win32 executable running in full trust. ```xml ... ``` -------------------------------- ### run() Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/npm-usage Creates a packaged layout, registers the application, and launches the packaged application. It accepts options to control input folder, command-line arguments, data cleaning, debugging, and more. ```APIDOC ## run() ### Description Creates packaged layout, registers the Application, and launches the packaged application. ### Signature ```typescript function run(options: RunOptions): Promise ``` ### Options #### Path Parameters - **inputFolder** (string) - Required - Input folder containing the app to run #### Query Parameters - **args** (string | undefined) - No - Command-line arguments to pass to the application - **clean** (boolean | undefined) - No - Remove the existing package's application data (LocalState, settings, etc.) before re-deploying. By default, application data is preserved across re-deployments. - **debugOutput** (boolean | undefined) - No - Capture OutputDebugString messages and first-chance exceptions from the launched application. Only one debugger can attach to a process at a time, so other debuggers (Visual Studio, VS Code) cannot be used simultaneously. Use --no-launch instead if you need to attach a different debugger. Cannot be combined with --no-launch or --json. - **detach** (boolean | undefined) - No - Launch the application and return immediately without waiting for it to exit. Useful for CI/automation where you need to interact with the app after launch. Prints the PID to stdout (or in JSON with --json). - **json** (boolean | undefined) - No - Format output as JSON - **manifest** (string | undefined) - No - Path to the Package.appxmanifest (default: auto-detect from input folder or current directory) - **noLaunch** (boolean | undefined) - No - Only create the debug identity and register the package without launching the application - **outputAppxDirectory** (string | undefined) - No - Output directory for the loose layout package. If not specified, a directory named AppX inside the input-folder directory will be used. - **symbols** (boolean | undefined) - No - Download symbols from Microsoft Symbol Server for richer native crash analysis. Only used with --debug-output. First run downloads symbols and caches them locally; subsequent runs use the cache. - **unregisterOnExit** (boolean | undefined) - No - Unregister the development package after the application exits. Only removes packages registered in development mode. - **withAlias** (boolean | undefined) - No - Launch the app using its execution alias instead of AUMID activation. The app runs in the current terminal with inherited stdin/stdout/stderr. Requires a uap5:ExecutionAlias in the manifest. Use "winapp manifest add-alias" to add an execution alias to the manifest. _Also accepts CommonOptions (`quiet`, `verbose`, `cwd`)._ ``` -------------------------------- ### Create and Update App Submission Source: https://learn.microsoft.com/en-us/windows/apps/publish/store-submission-api This Node.js example demonstrates how to use the Microsoft Store Submission API to manage an app submission. It covers getting access tokens, checking draft status, managing packages (getting, updating, committing), and updating application metadata and listings. ```APIDOC ## Node.js Sample: Microsoft Store Submission API ### Description This sample demonstrates how to interact with the Microsoft Store Submission API using Node.js to manage an app submission. It covers various operations such as authentication, retrieving submission status, managing application packages, and updating metadata. ### Prerequisites - Node.js installed - `node-fetch` v2 library installed (`npm install node-fetch@2`) - Partner Center account details (Seller ID, Application ID) - Microsoft Entra ID application credentials (Client ID, Client Secret, Tenant ID) ### Core Operations Demonstrated #### 1. Authentication - **Description**: Obtains an access token required for authenticating API requests. - **Method**: Implicitly handled by `submissionClient.getAccessToken()`. #### 2. Get Application Draft Status - **Description**: Retrieves the current draft status of the application submission. - **Method**: `GET` - **Endpoint**: Uses `client.productDraftStatusPollingUrlTemplate`. #### 3. Get Application Packages - **Description**: Fetches the list of packages associated with the application submission. - **Method**: `GET` - **Endpoint**: Uses `client.packagesUrlTemplate`. #### 4. Get Single Package Details - **Description**: Retrieves details for a specific package using its ID. - **Method**: `GET` - **Endpoint**: Uses `client.packageByIdUrlTemplate` with a package ID. #### 5. Update Entire Package Set - **Description**: Updates all packages in the submission. This involves modifying the `installerParameters` for each package and sending a PUT request. - **Method**: `PUT` - **Endpoint**: Uses `client.packagesUrlTemplate`. - **Request Body**: A JSON object containing a `packages` array with updated package information. #### 6. Update Single Package's Installer Parameters - **Description**: Updates specific fields, like `installerParameters`, for a single package using a PATCH request. - **Method**: `PATCH` - **Endpoint**: Uses `client.packageByIdUrlTemplate` with a package ID. - **Request Body**: The updated package object with modified fields. #### 7. Commit Packages - **Description**: Commits the updated packages, initiating the upload process. - **Method**: `POST` - **Endpoint**: Uses `client.packagesCommitUrlTemplate`. #### 8. Poll for Upload Completion - **Description**: Periodically checks the submission status until the upload process is finished. - **Method**: `GET` (within a polling loop) - **Endpoint**: Uses `client.productDraftStatusPollingUrlTemplate`. #### 9. Get Application Metadata (All Modules) - **Description**: Retrieves all metadata associated with the application, including details for different modules. - **Method**: `GET` - **Endpoint**: Uses `client.appMetadataUrlTemplate`. #### 10. Get Application Metadata (Listings) - **Description**: Fetches the metadata specifically for the application's listings (e.g., descriptions, images). - **Method**: `GET` - **Endpoint**: Uses `client.appListingsFetchMetadataUrlTemplate`. #### 11. Update Listings Metadata - **Description**: Updates the metadata for the application's listings, such as the description for a specific language. - **Method**: `PUT` - **Endpoint**: Uses `client.appMetadataUrlTemplate`. - **Request Body**: A JSON object containing updated `listings` information. #### 12. Get All Listings Assets - **Description**: Retrieves all assets related to the application's listings. - **Method**: `GET` - **Endpoint**: Uses `client.listingAssetsUrlTemplate`. ### Configuration Notes - Ensure `SellerId`, `ApplicationId`, `ClientId`, `ClientSecret`, and `tenantid` are correctly configured in the `./Configuration` file or environment variables. ``` -------------------------------- ### App Installer Configuration Source: https://learn.microsoft.com/en-us/windows/apps/dev-tools/winapp-cli/guides/electron-packaging An example of an .appinstaller file used for automatic updates of MSIX packages. Configure the Uri, Version, and MainPackage details according to your distribution. ```XML ``` -------------------------------- ### Initialize React Native for Desktop App for Microsoft Store Source: https://learn.microsoft.com/en-us/windows/apps/publish/msstore-dev-cli/commands Use the `init` command to set up your React Native for Desktop application for publishing to the Microsoft Store. Provide the local path to your project. For React Native for Desktop projects, `Npm` and `Yarn` are supported. ```bash msstore init "C:\path\to\react_native_app" ``` -------------------------------- ### Launch a file with its default handler (C++/WinRT) Source: https://learn.microsoft.com/en-us/windows/apps/develop/launch/launch-the-default-app-for-a-file This C++/WinRT example demonstrates launching a file using its default handler. It retrieves the file from the installed location and then calls `LaunchFileAsync`. ```C++/WinRT Windows::Foundation::IAsyncAction MainPage::DefaultLaunch() { auto installFolder{ Windows::ApplicationModel::Package::Current().InstalledLocation() }; Windows::Storage::StorageFile file{ co_await installFolder.GetFileAsync(L"images\test.png") }; if (file) { // Launch the retrieved file bool success = co_await Windows::System::Launcher::LaunchFileAsync(file); if (success) { // File launched } else { // File launch failed } } else { // Could not find file } } ``` -------------------------------- ### Automate Environment Setup with WinGet Configuration Source: https://learn.microsoft.com/en-us/windows/apps/get-started/start-here Use this PowerShell command to automatically install Visual Studio 2026 with the required workloads and enable Developer Mode on your device. ```PowerShell winget configure -f https://aka.ms/winui-config ```