Share via


Procedura: Programmazione della finestra di messaggio eccezione

È possibile utilizzare la finestra di messaggio eccezione nelle applicazioni per offrire un controllo maggiore sull'invio e la ricezione di messaggi rispetto a quello garantito dalla classe MessageBox. Per ulteriori informazioni, vedere Programmazione della finestra di messaggio eccezione. Per informazioni su come ottenere e distribuire il file dll della finestra di messaggio eccezione, vedere Distribuzione di un'applicazione finestra di messaggio eccezione.

Procedura

Per gestire un'eccezione tramite la finestra di messaggio eccezione

  1. Aggiungere un riferimento all'assembly Microsoft.ExceptionMessageBox.dll nel progetto di codice gestito.

  2. (Facoltativo) Aggiungere una direttiva using (C#) o Imports (Microsoft Visual Basic .NET) per utilizzare lo spazio dei nomi Microsoft.SqlServer.MessageBox.

  3. Creare un blocco Try-Catch per gestire l'eccezione anticipata.

  4. All'interno del blocco catch creare un'istanza della classe ExceptionMessageBox. Passare l'oggetto Exception gestito da un blocco try-catch.

  5. (Facoltativo) Impostare una o più delle proprietà seguenti su ExceptionMessageBox:

  6. Chiamare il metodo Show. Passare la finestra padre alla quale appartiene la finestra di messaggio eccezione.

  7. (Facoltativo) Annotare il valore dell'enumerazione DialogResult restituita se è necessario determinare su quale pulsante l'utente ha fatto clic.

Per visualizzare la finestra di messaggio eccezione senza un'eccezione

  1. Aggiungere un riferimento all'assembly Microsoft.ExceptionMessageBox.dll nel progetto di codice gestito.

  2. (Facoltativo) Aggiungere una direttiva using (C#) o Imports (Visual Basic .NET) per utilizzare lo spazio dei nomi Microsoft.SqlServer.MessageBox.

  3. Creare un'istanza della classe ExceptionMessageBox. Passare il testo del messaggio come valore String.

  4. (Facoltativo) Impostare una o più delle proprietà seguenti su ExceptionMessageBox:

  5. Chiamare il metodo Show. Passare la finestra padre alla quale appartiene la finestra di messaggio eccezione.

  6. (Facoltativo) Annotare il valore dell'enumerazione DialogResult restituita se è necessario determinare su quale pulsante l'utente ha fatto clic.

Per visualizzare la finestra di messaggio eccezione con pulsanti personalizzati

  1. Aggiungere un riferimento all'assembly Microsoft.ExceptionMessageBox.dll nel progetto di codice gestito.

  2. (Facoltativo) Aggiungere una direttiva using (C#) o Imports (Visual Basic .NET) per utilizzare lo spazio dei nomi Microsoft.SqlServer.MessageBox.

  3. Creare un'istanza della classe ExceptionMessageBox in uno dei due modi seguenti:

    • Passare l'oggetto Exception gestito da un blocco try-catch.

    • Passare il testo del messaggio come valore String.

  4. Impostare uno dei seguenti valori per Buttons:

    • AbortRetryIgnore: visualizza i pulsanti Interrompi, Riprova e Ignora.

    • Custom: visualizza pulsanti personalizzati.

    • OK: visualizza il pulsante OK.

    • OKCancel: visualizza i pulsanti OK e Annulla.

    • RetryCancel: visualizza i pulsanti Riprova e Annulla.

    • YesNo: visualizza i pulsanti e No.

    • YesNoCancel: visualizza i pulsanti , No e Annulla.

  5. (Facoltativo) Se si utilizzano pulsanti personalizzati, chiamare uno degli overload del metodo SetButtonText per specificare il testo per un massimo di cinque pulsanti personalizzati.

  6. Chiamare il metodo Show. Passare la finestra padre alla quale appartiene la finestra di messaggio eccezione.

  7. (Facoltativo) Annotare il valore dell'enumerazione DialogResult restituita se è necessario determinare su quale pulsante l'utente ha fatto clic. Se si utilizzano pulsanti personalizzati, annotare il valore di ExceptionMessageBoxDialogResult per la proprietà CustomDialogResult per determinare su quale pulsante personalizzato l'utente ha fatto clic.

Per consentire agli utenti di decidere se visualizzare la finestra di messaggio eccezione

  1. Aggiungere un riferimento all'assembly Microsoft.ExceptionMessageBox.dll nel progetto di codice gestito.

  2. (Facoltativo) Aggiungere una direttiva using (C#) o Imports (Visual Basic .NET) per utilizzare lo spazio dei nomi Microsoft.SqlServer.MessageBox.

  3. Creare un'istanza della classe ExceptionMessageBox in uno dei due modi seguenti:

    • Passare l'oggetto Exception gestito da un blocco try-catch.

    • Passare il testo del messaggio come valore String.

  4. Impostare la proprietà ShowCheckbox()()()() su true.

  5. (Facoltativo) Specificare il testo per chiedere all'utente di decidere se visualizzare nuovamente la finestra di messaggio eccezione per CheckboxText()()()(). Il testo predefinito è "Non visualizzare più questo messaggio".

  6. Se è necessario mantenere la decisione dell'utente solo per la durata dell'esecuzione dell'applicazione, impostare il valore di IsCheckboxChecked()()()() su una variabile Boolean globale. Valutare questo valore prima di creare un'istanza della finestra di messaggio eccezione.

  7. Se è necessario archiviare in modo permanente la decisione di un utente, eseguire le operazioni seguenti:

    1. Chiamare il metodo CreateSubKey(String) per aprire una chiave del Registro di sistema personalizzata utilizzata dall'applicazione e impostare CheckboxRegistryKey()()()() sull'oggetto RegistryKey restituito.

    2. Impostare CheckboxRegistryValue()()()() sul nome del valore del Registro di sistema utilizzato.

    3. Impostare CheckboxRegistryMeansDoNotShowDialog()()()() su true.

    4. Chiamare il metodo Show. La chiave del Registro di sistema specificata viene valutata e la finestra di messaggio eccezione viene visualizzata solo se i dati archiviati in tale chiave sono pari a 0. Se la finestra di dialogo viene visualizzata e l'utente seleziona la casella di controllo prima di fare clic su un pulsante, i dati nella chiave del Registro di sistema vengono impostati su 1.

Esempio

In questo esempio viene utilizzata la finestra di messaggio eccezione con il solo pulsante OK per visualizzare informazioni di un'eccezione dell'applicazione che include l'eccezione gestita con ulteriori informazioni specifiche dell'applicazione.

          try
            {
                // Do something that may generate an exception.
                throw new ApplicationException("An error has occured");
            }
            catch (ApplicationException ex)
            {
                // Define a new top-level error message.
                string str = "The action failed.";

                // Add the new top-level message to the handled exception.
                ApplicationException exTop = new ApplicationException(str, ex);
                exTop.Source = this.Text;

                // Show an exception message box with an OK button (the default).
                ExceptionMessageBox box = new ExceptionMessageBox(exTop);
                box.Show(this);
            }
Try
    ' Do something that may generate an exception.
    Throw New ApplicationException("An error has occured")
Catch ex As ApplicationException
    ' Define a new top-level error message.
    Dim str As String = "The action failed."

    ' Add the new top-level message to the handled exception.
    Dim exTop As ApplicationException = New ApplicationException(str, ex)
    exTop.Source = Me.Text

    ' Show an exception message box with an OK button (the default).
    Dim box As ExceptionMessageBox = New ExceptionMessageBox(exTop)
    box.Show(Me)
End Try

In questo esempio viene utilizzata la finestra di messaggio eccezione con i pulsanti e No che possono essere scelti dall'utente.

           // Define the message and caption to display.
            string str = @"Are you sure you want to delete file 'c:\somefile.txt'?";
            string caption = "Confirm File Deletion";

            // Show the exception message box with Yes and No buttons.
            ExceptionMessageBox box = new ExceptionMessageBox(str,
                caption, ExceptionMessageBoxButtons.YesNo,
                ExceptionMessageBoxSymbol.Question,
                ExceptionMessageBoxDefaultButton.Button2);

            if (DialogResult.Yes == box.Show(this))
            {
                // Delete the file.
            }
' Define the message and caption to display.
Dim str As String = "Are you sure you want to delete file 'c:\somefile.txt'?"
Dim caption As String = "Confirm File Deletion"

' Show the exception message box with Yes and No buttons.
Dim box As ExceptionMessageBox = New ExceptionMessageBox(str, _
 caption, ExceptionMessageBoxButtons.YesNo, _
 ExceptionMessageBoxSymbol.Question, _
 ExceptionMessageBoxDefaultButton.Button2)

If Windows.Forms.DialogResult.Yes = box.Show(Me) Then
    ' Delete the file.
End If

In questo esempio viene utilizzata la finestra di messaggio eccezione con pulsanti personalizzati.

         try
            {
                // Do something that may cause an exception.
                throw new ApplicationException("An error has occured");
            }
            catch (ApplicationException ex)
            {
                string str = "Action failed. What do you want to do?";
                ApplicationException exTop = new ApplicationException(str, ex);
                exTop.Source = this.Text;

                // Show the exception message box with three custom buttons.
                ExceptionMessageBox box = new ExceptionMessageBox(exTop);

                // Set the names of the three custom buttons.
                box.SetButtonText("Skip", "Retry", "Stop Processing");

                // Set the Retry button as the default.
                box.DefaultButton = ExceptionMessageBoxDefaultButton.Button2;
                box.Symbol = ExceptionMessageBoxSymbol.Question;
                box.Buttons = ExceptionMessageBoxButtons.Custom;

                box.Show(this);

                // Do something, depending on the button that the user clicks.
                switch (box.CustomDialogResult)
                {
                    case ExceptionMessageBoxDialogResult.Button1:
                        // Skip action
                        break;
                    case ExceptionMessageBoxDialogResult.Button2:
                        // Retry action
                        break;
                    case ExceptionMessageBoxDialogResult.Button3:
                        // Stop processing action
                        break;
                }
            }
Try
    ' Do something that may cause an exception.
    Throw New ApplicationException("An error has occured")
Catch ex As ApplicationException
    Dim str As String = "Action failed. What do you want to do?"
    Dim exTop As ApplicationException = New ApplicationException(str, ex)
    exTop.Source = Me.Text

    ' Show the exception message box with three custom buttons.
    Dim box As ExceptionMessageBox = New ExceptionMessageBox(exTop)

    ' Set the names of the three custom buttons.
    box.SetButtonText("Skip", "Retry", "Stop Processing")

    ' Set the Retry button as the default.
    box.DefaultButton = ExceptionMessageBoxDefaultButton.Button2
    box.Symbol = ExceptionMessageBoxSymbol.Question
    box.Buttons = ExceptionMessageBoxButtons.Custom

    box.Show(Me)

    ' Do something, depending on the button that the user clicks.
    Select Case box.CustomDialogResult
        Case ExceptionMessageBoxDialogResult.Button1
            ' Skip action
        Case ExceptionMessageBoxDialogResult.Button2
            ' Retry action
        Case ExceptionMessageBoxDialogResult.Button3
            ' Stop processing action
    End Select
End Try

In questo esempio viene utilizzata la casella di controllo per determinare se visualizzare la finestra di messaggio eccezione.

         try
            {
                // Do something that may cause an exception.
                throw new ApplicationException("An error has occured.");
            }
            catch (ApplicationException ex)
            {
                string str = "The action failed.";
                ApplicationException exTop = new ApplicationException(str, ex);
                exTop.Source = this.Text;

                // Show a message box if the global variable is true.
                if (alwaysShow)
                {
                    ExceptionMessageBox box = new ExceptionMessageBox(exTop);
                    box.ShowCheckBox = true;
                    box.IsCheckBoxChecked = true;
                    box.CheckBoxText = "Always show this message";
                    box.Show(this);

                    // Set the global variable.
                    alwaysShow = box.IsCheckBoxChecked;
                }
            }
Try
    ' Do something that may cause an exception.
    Throw New ApplicationException("An error has occured.")
Catch ex As ApplicationException
    Dim str As String = "The action failed."
    Dim exTop As ApplicationException = New ApplicationException(str, ex)
    exTop.Source = Me.Text

    ' Show a message box if the global variable is true.
    If alwaysShow Then
        Dim box As ExceptionMessageBox = New ExceptionMessageBox(exTop)
        box.ShowCheckBox = True
        box.IsCheckBoxChecked = True
        box.CheckBoxText = "Always show this message"
        box.Show(Me)

        ' Set the global variable.
        alwaysShow = box.IsCheckBoxChecked
    End If
End Try

In questo esempio vengono utilizzate la casella di controllo e una chiave del Registro di sistema per determinare se visualizzare la finestra di messaggio eccezione.

          try
            {
                // Do something that could generate an exception.
                throw new ApplicationException("An error has occured.");
            }
            catch (ApplicationException ex)
            {
                string str = "The action failed. Do you want to continue?";
                ApplicationException exTop = new ApplicationException(str, ex);
                exTop.Source = this.Text;

                // Show a message box with Yes and No buttons
                ExceptionMessageBox box = new ExceptionMessageBox(exTop,
                    ExceptionMessageBoxButtons.YesNo,
                    ExceptionMessageBoxSymbol.Question,
                    ExceptionMessageBoxDefaultButton.Button2);

                // Enable the check box.
                box.ShowCheckBox = true;

                // Define the registry key to use.
                box.CheckBoxRegistryKey =
                    Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
                    @"Software\TestApp");
                box.CheckBoxRegistryValue = "DontShowActionFailedMessage";
                box.CheckBoxRegistryMeansDoNotShowDialog = true;
                box.DefaultDialogResult = DialogResult.Yes;

                // The message box won�t be displayed if the
                // "DontShowActionFailedMessage" value of the registry key 
                // contains a non-zero value.
                if (box.Show(this) == DialogResult.No)
                {
                    // Do something if the user clicks the No button.
                    this.Close();
                }
            }
Try
    ' Do something that could generate an exception.
    Throw New ApplicationException("An error has occured.")
Catch ex As ApplicationException
    Dim str As String = "The action failed. Do you want to continue?"
    Dim exTop As ApplicationException = New ApplicationException(str, ex)
    exTop.Source = Me.Text

    ' Show a message box with Yes and No buttons
    Dim box As ExceptionMessageBox = New ExceptionMessageBox(exTop, _
     ExceptionMessageBoxButtons.YesNo, _
     ExceptionMessageBoxSymbol.Question, _
     ExceptionMessageBoxDefaultButton.Button2)

    ' Enable the check box.
    box.ShowCheckBox = True

    ' Define the registry key to use.
    box.CheckBoxRegistryKey = _
    Microsoft.Win32.Registry.CurrentUser.CreateSubKey( _
     "Software\TestApp")
    box.CheckBoxRegistryValue = "DontShowActionFailedMessage"
    box.CheckBoxRegistryMeansDoNotShowDialog = True
    box.DefaultDialogResult = Windows.Forms.DialogResult.Yes

    ' The message box won�t be displayed if the
    ' "DontShowActionFailedMessage" value of the registry key 
    ' contains a non-zero value.
    If box.Show(Me) = Windows.Forms.DialogResult.No Then
        ' Do something if the user clicks the No button.
        Me.Close()
    End If
End Try

In questo esempio viene utilizzata la finestra di messaggio eccezione per visualizzare informazioni aggiuntive utili per la risoluzione dei problemi o il debug.

          try
            {
                // Do something that you don't expect to generate an exception.
                throw new ApplicationException("Failed to connect to the server.");
            }
            catch (ApplicationException ex)
            {
                string str = "An unexpected error occurred. Please call Helpdesk.";
                ApplicationException exTop = new ApplicationException(str, ex);
                exTop.Source = this.Text;

                // Information in the Data property of an exception that has a name
                // beginning with "HelpLink.Advanced" is shown when the user
                // clicks the Advanced Information button of the exception message
                // box dialog box.
                exTop.Data.Add("AdvancedInformation.FileName", "application.dll");
                exTop.Data.Add("AdvancedInformation.FilePosition", "line 355");
                exTop.Data.Add("AdvancedInformation.UserContext", "single user mode");

                // Show the exception message box with additional information that 
                // is helpful when a user calls technical support.
                ExceptionMessageBox box = new ExceptionMessageBox(exTop);

                box.Show(this);
            }
Try
    ' Do something that you don't expect to generate an exception.
    Throw New ApplicationException("Failed to connect to the server.")
Catch ex As ApplicationException
    Dim str As String = "An unexpected error occurred. Please call Helpdesk."
    Dim exTop As ApplicationException = New ApplicationException(str, ex)
    exTop.Source = Me.Text

    ' Information in the Data property of an exception that has a name
    ' beginning with "HelpLink.Advanced" is shown when the user
    ' clicks the Advanced Information button of the exception message
    ' box dialog box.
    exTop.Data.Add("AdvancedInformation.FileName", "application.dll")
    exTop.Data.Add("AdvancedInformation.FilePosition", "line 355")
    exTop.Data.Add("AdvancedInformation.UserContext", "single user mode")

    ' Show the exception message box with additional information that 
    ' is helpful when a user calls technical support.
    Dim box As ExceptionMessageBox = New ExceptionMessageBox(exTop)

    box.Show(Me)

End Try