Share via


Procedura dettagliata: Creare un programma di installazione personalizzato per un'applicazione ClickOnce

Qualsiasi applicazione ClickOnce basata su un file .exe può essere installata e aggiornata automaticamente da un programma di installazione personalizzato. Un programma di installazione personalizzato può implementare un'esperienza utente personalizzata durante l'installazione, incluse le finestre di dialogo personalizzate per le operazioni di sicurezza e manutenzione. Per eseguire operazioni di installazione, il programma di installazione personalizzato usa la InPlaceHostingManager classe . Questa procedura dettagliata illustra come creare un programma di installazione personalizzato che installa automaticamente un'applicazione ClickOnce.

Nota

La ApplicationDeployment classe e le API nello System.Deployment.Application spazio dei nomi non sono supportate in .NET Core e .NET 5 e versioni successive. In .NET 7 è supportato un nuovo metodo di accesso alle proprietà di distribuzione dell'applicazione. Per altre informazioni, vedere Accedere alle proprietà di distribuzione ClickOnce in .NET. .NET 7 non supporta l'equivalente dei metodi ApplicationDeployment.

Prerequisiti

Per creare un programma di installazione dell'applicazione ClickOnce personalizzato

  1. Nell'applicazione ClickOnce aggiungere riferimenti a System.Deployment e System.Windows.Forms.

  2. Aggiungere una nuova classe all'applicazione e specificare qualsiasi nome. Questa procedura dettagliata usa il nome MyInstaller.

  3. Aggiungere le direttive o using seguenti Imports all'inizio della nuova classe.

    using System.Deployment.Application;
    using System.Windows.Forms;
    
  4. Aggiungere i metodi seguenti alla classe .

    Questi metodi chiamano InPlaceHostingManager metodi per scaricare il manifesto della distribuzione, dichiarare le autorizzazioni appropriate, chiedere all'utente l'autorizzazione per l'installazione e quindi scaricare e installare l'applicazione nella cache ClickOnce. Un programma di installazione personalizzato può specificare che un'applicazione ClickOnce è pre-attendibile o può rinviare la decisione di attendibilità alla chiamata al AssertApplicationRequirements metodo. Questo codice pre-considera attendibile l'applicazione.

    Nota

    Le autorizzazioni assegnate dal pre-trusting non possono superare le autorizzazioni del codice del programma di installazione personalizzato.

    InPlaceHostingManager iphm = null;
    
    public void InstallApplication(string deployManifestUriStr)
    {
        try
        {
            Uri deploymentUri = new Uri(deployManifestUriStr);
            iphm = new InPlaceHostingManager(deploymentUri, false);
        }
        catch (UriFormatException uriEx)
        {
            MessageBox.Show("Cannot install the application: " + 
                "The deployment manifest URL supplied is not a valid URL. " +
                "Error: " + uriEx.Message);
            return;
        }
        catch (PlatformNotSupportedException platformEx)
        {
            MessageBox.Show("Cannot install the application: " + 
                "This program requires Windows XP or higher. " +
                "Error: " + platformEx.Message);
            return;
        }
        catch (ArgumentException argumentEx)
        {
            MessageBox.Show("Cannot install the application: " + 
                "The deployment manifest URL supplied is not a valid URL. " +
                "Error: " + argumentEx.Message);
            return;
        }
    
        iphm.GetManifestCompleted += new EventHandler<GetManifestCompletedEventArgs>(iphm_GetManifestCompleted);
        iphm.GetManifestAsync();
    }
    
    void iphm_GetManifestCompleted(object sender, GetManifestCompletedEventArgs e)
    {
        // Check for an error.
        if (e.Error != null)
        {
            // Cancel download and install.
            MessageBox.Show("Could not download manifest. Error: " + e.Error.Message);
            return;
        }
    
        // bool isFullTrust = CheckForFullTrust(e.ApplicationManifest);
    
        // Verify this application can be installed.
        try
        {
            // the true parameter allows InPlaceHostingManager
            // to grant the permissions requested in the applicaiton manifest.
            iphm.AssertApplicationRequirements(true) ; 
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred while verifying the application. " +
                "Error: " + ex.Message);
            return;
        }
    
        // Use the information from GetManifestCompleted() to confirm 
        // that the user wants to proceed.
        string appInfo = "Application Name: " + e.ProductName;
        appInfo += "\nVersion: " + e.Version;
        appInfo += "\nSupport/Help Requests: " + (e.SupportUri != null ?
            e.SupportUri.ToString() : "N/A");
        appInfo += "\n\nConfirmed that this application can run with its requested permissions.";
        // if (isFullTrust)
        // appInfo += "\n\nThis application requires full trust in order to run.";
        appInfo += "\n\nProceed with installation?";
    
        DialogResult dr = MessageBox.Show(appInfo, "Confirm Application Install",
            MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
        if (dr != System.Windows.Forms.DialogResult.OK)
        {
            return;
        }
    
        // Download the deployment manifest. 
        iphm.DownloadProgressChanged += new EventHandler<DownloadProgressChangedEventArgs>(iphm_DownloadProgressChanged);
        iphm.DownloadApplicationCompleted += new EventHandler<DownloadApplicationCompletedEventArgs>(iphm_DownloadApplicationCompleted);
    
        try
        {
            // Usually this shouldn't throw an exception unless AssertApplicationRequirements() failed, 
            // or you did not call that method before calling this one.
            iphm.DownloadApplicationAsync();
        }
        catch (Exception downloadEx)
        {
            MessageBox.Show("Cannot initiate download of application. Error: " +
                downloadEx.Message);
            return;
        }
    }
    
    /*
    private bool CheckForFullTrust(XmlReader appManifest)
    {
        if (appManifest == null)
        {
            throw (new ArgumentNullException("appManifest cannot be null."));
        }
    
        XAttribute xaUnrestricted =
            XDocument.Load(appManifest)
                .Element("{urn:schemas-microsoft-com:asm.v1}assembly")
                .Element("{urn:schemas-microsoft-com:asm.v2}trustInfo")
                .Element("{urn:schemas-microsoft-com:asm.v2}security")
                .Element("{urn:schemas-microsoft-com:asm.v2}applicationRequestMinimum")
                .Element("{urn:schemas-microsoft-com:asm.v2}PermissionSet")
                .Attribute("Unrestricted"); // Attributes never have a namespace
    
        if (xaUnrestricted != null)
            if (xaUnrestricted.Value == "true")
                return true;
    
        return false;
    }
    */
    
    void iphm_DownloadApplicationCompleted(object sender, DownloadApplicationCompletedEventArgs e)
    {
        // Check for an error.
        if (e.Error != null)
        {
            // Cancel download and install.
            MessageBox.Show("Could not download and install application. Error: " + e.Error.Message);
            return;
        }
    
        // Inform the user that their application is ready for use. 
        MessageBox.Show("Application installed! You may now run it from the Start menu.");
    }
    
    void iphm_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        // you can show percentage of task completed using e.ProgressPercentage
    }
    
  5. Per tentare l'installazione dal codice, chiamare il InstallApplication metodo . Ad esempio, se è stata denominata la classe MyInstaller, è possibile chiamare InstallApplication nel modo seguente.

    MyInstaller installer = new MyInstaller();
    installer.InstallApplication(@"\\myServer\myShare\myApp.application");
    MessageBox.Show("Installer object created.");
    

Passaggi successivi

Un'applicazione ClickOnce può anche aggiungere logica di aggiornamento personalizzata, inclusa un'interfaccia utente personalizzata da visualizzare durante il processo di aggiornamento. Per ulteriori informazioni, vedere UpdateCheckInfo. Un'applicazione ClickOnce può anche eliminare la voce di menu Start standard, il collegamento e la voce Installazione applicazioni usando un <customUX> elemento . Per altre informazioni, vedere <elemento entryPoint> e ShortcutAppId.