You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在VS 2017中创建Brokered Windows Runtime Component的步骤问询

Step-by-Step Guide to Brokered Windows Runtime Components for UWP (Side-Loading + Disabled Namespaces)

Hey there! I’ve spent a fair amount of time working with Brokered Windows Runtime Components for Windows 10 UWP apps, so let’s unpack those vague steps from your guide with clear, actionable details. We’ll break this down into 4 core parts: building the brokered component, registering it, configuring your UWP app, and side-loading the app.

1. Create & Configure the Brokered Windows Runtime Component

This component acts as a "middleman" to access UWP-restricted APIs. Here’s how to set it up properly:

  • Create the component project: Open Visual Studio, go to Create a new project, search for Windows Runtime Component (Desktop) (not the UWP version), name it something like MyBrokeredApiWrapper.
  • Match Windows versions: In the project properties, set the Target Framework and Minimum Version to match your UWP app (e.g., Windows 10, version 1809 or newer).
  • Add restricted namespace references: Right-click the project → Add → Reference. Under Windows Universal → Extensions, check the boxes for the namespaces you need (e.g., Windows.Management.Deployment for package installation, Windows.System.UserProfile for user profile data).
  • Implement your wrapper class: Write a public class that wraps the restricted API calls. Make sure to add these attributes to the class to enable UWP access:
    using Windows.Foundation.Metadata;
    using System.Runtime.InteropServices;
    
    [AllowForWeb]
    [MarshalingBehavior(MarshalingBehavior.Agile)]
    public class DeploymentHelper
    {
        public async Task<bool> InstallPackageAsync(string packagePath)
        {
            // Use the restricted Windows.Management.Deployment API here
            var packageManager = new Windows.Management.Deployment.PackageManager();
            try
            {
                await packageManager.AddPackageAsync(new Uri(packagePath), null, DeploymentOptions.None);
                return true;
            }
            catch (Exception ex)
            {
                // Handle error
                return false;
            }
        }
    }
    
  • Sign the component: Brokered components require strong naming. Right-click the project → Properties → Signing → Check Sign the assembly, then create a new strong name key file (.pfx).
  • Build the component: Generate a Release build (Debug works for testing, but Release is required for production). You’ll get a .winmd file and .dll in the output folder.

2. Register the Brokered Component with Windows

This is often the most vague step—you need to add registry entries so UWP can find and trust the component:

  • Create a PowerShell registration script: Make a file named RegisterBrokeredComponent.ps1 with this content (replace paths and class IDs with your own):
    # Replace with your component's output path
    $componentDir = "C:\Projects\MyBrokeredApiWrapper\bin\Release\netcoreapp3.1"
    # Replace with your component's unique identifier (use your class namespace + name)
    $componentId = "MyBrokeredApiWrapper.DeploymentHelper"
    $regPath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\EmbeddedMode\Broker\$componentId"
    
    # Create registry key and properties
    New-Item -Path $regPath -Force
    New-ItemProperty -Path $regPath -Name "Path" -Value $componentDir -PropertyType String
    New-ItemProperty -Path $regPath -Name "RuntimeType" -Value "WinRT" -PropertyType String
    New-ItemProperty -Path $regPath -Name "ActivatableClassId" -Value $componentId -PropertyType String
    
  • Run the script as Administrator: Right-click PowerShell → Run as administrator, navigate to the script’s folder, and execute it with .\RegisterBrokeredComponent.ps1.

3. Configure Your UWP App to Use the Brokered Component

Now link your UWP app to the component and request the necessary permissions:

  • Add the component reference: Right-click your UWP project → Add → Reference → Browse, then select the .winmd file from your brokered component’s output folder.
  • Modify the Package.appxmanifest: Open the manifest in code view (right-click → View Code) to add restricted capabilities and component registration:
    1. Add the restricted capabilities namespace to the root Package element:
      <Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
               xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
               IgnorableNamespaces="uap mp rescap">
      
    2. Add the required restricted capability (match the API you’re using—example for package deployment):
      <Capabilities>
          <rescap:Capability Name="packageManagement" />
          <!-- Add other restricted capabilities here if needed -->
      </Capabilities>
      
    3. Register the brokered component under the Extensions node:
      <Extensions>
          <Extension Category="windows.brokerComponent">
              <BrokerComponent>
                  <Path>MyBrokeredApiWrapper.dll</Path>
                  <ActivatableClass ActivatableClassId="MyBrokeredApiWrapper.DeploymentHelper" ThreadingModel="both" />
              </BrokerComponent>
          </Extension>
      </Extensions>
      
  • Call the component from UWP code: In your UWP app (e.g., MainPage.xaml.cs), instantiate the wrapper class and use its methods:
    private async void InstallButton_Click(object sender, RoutedEventArgs e)
    {
        var helper = new MyBrokeredApiWrapper.DeploymentHelper();
        bool success = await helper.InstallPackageAsync("C:\\Path\\To\\Your\\AppPackage.appx");
        // Handle success/failure
    }
    

4. Side-Load the UWP App

To run the app outside the Microsoft Store, enable side-loading and install the package:

  • Enable side-loading mode:
    • Via Settings: Go to Settings → Update & Security → Developer options → Toggle on Side-load apps.
    • Via PowerShell (admin): Run Set-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\AppModelUnlock -Name AllowAllTrustedApps -Value 1.
  • Generate the app package: Right-click your UWP project → Publish → Create App Packages → Select Side-load → Choose your output folder, then follow the wizard to generate the .appxbundle (or .appx) and certificate files.
  • Install the app:
    • Open the output folder, double-click Add-AppDevPackage.ps1, and run it as administrator. This will install the self-signed certificate and the app automatically.
    • Alternatively, use PowerShell (admin): Add-AppxPackage -Path "C:\Path\To\Your\UwpApp\UwpApp_1.0.0.0_x64.appxbundle".

Troubleshooting Tips

  • Ensure your UWP app and brokered component use the same architecture (x64/x86)—mismatches cause loading errors.
  • Check the Windows Event Viewer (Windows Logs → Application) for error logs tagged with your app or component name if things fail.
  • Double-check registry entries and manifest configurations—typos in class IDs or paths are common culprits.

内容的提问来源于stack exchange,提问作者Daniel Goudie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:52:19