Verwalten der URI-Protokollaktivierung in einer .NET-App

Durch die Protokollaktivierung (auch als Deep Linking oder URI-Aktivierung bezeichnet) kann eine andere App, ein Browser oder die Befehlszeile Ihre App starten, indem sie zu einem URI wie myapp://action?param=value navigieren.

Dieser Artikel enthält Code speziell für eine WPF-App. Vollständige Anleitungen finden Sie im Hauptartikel zur Handle-URI-Aktivierung . Ausführliche Informationen zur umfassenden Aktivierung mit dem Windows App SDK finden Sie unter Rich-Aktivierung mit der App-Lebenszyklus-API.

Registrieren für die Protokollaktivierung

Sie müssen Ihre App registrieren, damit sie Protokollaktivierungen verarbeiten kann. Bei einer entpackten App erfolgt die Registrierung im Code. Bei einer verpackten App registrieren Sie sich im App-Manifest.

Nicht gepackte Apps

Registrieren Sie für eine entpackte .NET-App (standardeinrichtung WPF/WinForms) Ihr Protokoll beim Start mithilfe von ActivationRegistrationManager. Registrierungen sind pro Benutzer und bleiben erhalten, daher ist es sicher, dies bei jedem Start aufzurufen.

In App.xaml.cs, überschreiben OnStartup:

using Microsoft.Windows.AppLifecycle;

protected override void OnStartup(StartupEventArgs e)
{
    // Register the URI scheme "myapp://" for this app.
    // For the logo, pass the exe path + resource index (or "" to use the default icon).
    string exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
    string logo = string.IsNullOrEmpty(exePath) ? "" : exePath + ",0";
    ActivationRegistrationManager.RegisterForProtocolActivation(
        "myapp",                // URI scheme (no "://")
        logo,                   // logo: exe path + resource index, or "" for default icon
        "My App",               // display name for the protocol
        exePath);               // path of this EXE; pass "" to default to the current process

    base.OnStartup(e);
}

Rufen Sie zum Bereinigen der Registrierung (z. B. in einem Deinstallationsschritt) auf ActivationRegistrationManager.UnregisterForProtocolActivation("myapp", "").

App-Paket

Deklarieren Sie für eine verpackte .NET-App das Protokoll in Package.appxmanifest unter dem Element <Applications><Application>:

<Applications>
  <Application ...>
    <Extensions>
      <uap:Extension Category="windows.protocol">
        <uap:Protocol Name="myapp">
          <uap:DisplayName>My App</uap:DisplayName>
        </uap:Protocol>
      </uap:Extension>
    </Extensions>
  </Application>
</Applications>

Stellen Sie sicher, dass der uap XML-Namespace für das Package Element deklariert ist: xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10".

Verwalten des Aktivierungsprozesses

Rufen Sie die Aktivierungsargumente mithilfe von AppInstance.GetCurrent() ab. GetActivatedEventArgs. Das folgende Beispiel enthält Code für eine entpackte WPF-App, die beim Start RegisterForProtocolActivation aufruft. Verpackte Apps erhalten die Aktivierung über die Manifestregistrierung, damit sie den RegisterForProtocolActivation Anruf überspringen können.

using Microsoft.Windows.AppLifecycle;
using Windows.ApplicationModel.Activation;

protected override void OnStartup(StartupEventArgs e)
{
    // Unpackaged apps only: register the protocol at startup.
    // Packaged apps (MSIX): skip these lines — the manifest handles registration.
    string exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
    string logo = string.IsNullOrEmpty(exePath) ? "" : exePath + ",0";
    ActivationRegistrationManager.RegisterForProtocolActivation(
        "myapp", logo, "My App", exePath);

    // Get the activation args for this specific launch.
    AppActivationArguments args = AppInstance.GetCurrent().GetActivatedEventArgs();
    if (args?.Kind == ExtendedActivationKind.Protocol)
    {
        var protocolArgs = (ProtocolActivatedEventArgs)args.Data;
        HandleProtocolActivation(protocolArgs.Uri);
    }

    base.OnStartup(e);
}

private void HandleProtocolActivation(Uri uri)
{
    // Navigate to or open content based on uri.AbsolutePath or uri.Query.
}

Hinweis

WPF- und Windows Forms Apps müssenAppInstance.GetCurrent().GetActivatedEventArgs() aufrufen, um URI-Aktivierungsdaten abzurufen. Im Gegensatz zu C++-Win32-Apps erhalten .NET Apps keine Aktivierungsargumente über einen Starteinstiegspunktparameter.

Verarbeitung von Einzelinstanz-Umleitungen

Wenn Ihre App nur eine Instanz gleichzeitig ausführen soll, verwenden Sie AppInstance.FindOrRegisterForKey, um nachfolgende URI-Starts an die laufende Instanz umzuleiten.

protected override void OnStartup(StartupEventArgs e)
{
    string exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
    string logo = string.IsNullOrEmpty(exePath) ? "" : exePath + ",0";
    ActivationRegistrationManager.RegisterForProtocolActivation(
        "myapp", logo, "My App", exePath);

    // Try to claim the "main" key. If another instance already has it, redirect and exit.
    AppInstance currentInstance = AppInstance.FindOrRegisterForKey("main");
    if (!currentInstance.IsCurrent)
    {
        var activationArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
        // Run the async redirect on a thread-pool thread to avoid a potential deadlock
        // with the WPF SynchronizationContext. Signal completion via an event so that
        // this code path exits cleanly without re-entering the STA message pump.
        var redirectCompleted = new System.Threading.ManualResetEventSlim(false);
        System.Threading.Tasks.Task.Run(async () =>
        {
            await currentInstance.RedirectActivationToAsync(activationArgs);
            redirectCompleted.Set();
        });
        redirectCompleted.Wait();
        Shutdown();
        return;
    }

    // This is the first instance. Subscribe to future activations.
    currentInstance.Activated += OnActivated;
    base.OnStartup(e);
}

private void OnActivated(object sender, AppActivationArguments args)
{
    Dispatcher.Invoke(() =>
    {
        if (args.Kind == ExtendedActivationKind.Protocol)
        {
            var protocolArgs = (ProtocolActivatedEventArgs)args.Data;
            HandleProtocolActivation(protocolArgs.Uri);
        }
        MainWindow?.Activate();
    });
}

Weitere Informationen zur App-Instancing finden Sie unter App-Instancing mit der App-Lebenszyklus-API.