2011-12-28 11 views
17

Proprio ora ho notato che Visual Studio mostra una finestra di messaggio con dettagli quando una proprietà è impostata su un valore non valido. Per esempio:Come posso visualizzare una finestra di messaggio con dettagli in WinForms?

E 'possibile effettuare questo tipo di finestra di messaggio in WinForms?

Ho provato il seguente codice:

MessageBox.Show("Error in Division Fill.\n" + ex.Message, 
       "Information",    
       MessageBoxButtons.OK, 
       MessageBoxIcon.Information, 
       MessageBoxOptions.RightAlign); 

Ma questo prodotto il seguente errore:

Error 24 The best overloaded method match for 'System.Windows.Forms.MessageBox.Show(string, string, System.Windows.Forms.MessageBoxButtons, System.Windows.Forms.MessageBoxIcon, System.Windows.Forms.MessageBoxDefaultButton)' has some invalid arguments

G:\Jagadeeswaran\Nov 17\MCS-SPS School\MCS-SPS School\Certificate\Transfer.cs 164 21 MCS-SPS School

Come posso correggere questo errore e ottenere una finestra di messaggio che mostra ulteriori dettagli?

+6

Ecco una finestra di dialogo personalizzata; non puoi ottenerlo usando uno degli overload standard di 'MessageBox.Show'. –

+0

Grazie. allora a cosa serve MessageBoxOptions. – Sagotharan

+1

Le 'MessageBoxOptions' sono documentate [qui] (http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxoptions.aspx). Non sono sicuro del motivo per cui hai pensato che "RightAlign" avesse qualcosa a che fare con la visualizzazione di "Dettagli". Semplicemente fa sì che il testo nella finestra di messaggio sia allineato a destra, come su un sistema RTL. –

risposta

24

Come altri hanno sottolineato, è necessario scrivere una finestra di dialogo personalizzata con le funzionalità desiderate. Per assistenza su questo, è possibile esaminare l'implementazione effettiva utilizzata da PropertyGrid per questa finestra di dialogo (magari con un decompilatore), che è, a partire da .NET 4.0, il tipo System.Windows.Forms.PropertyGridInternal.GridErrorDlg, interno all'assembly System.Windows.Forms.

I in realtà non lo consiglio (potrebbe irrompere in una versione futura), ma se ti senti veramente pigro, puoi usare direttamente questo tipo interno usando la riflessione.

// Get reference to the dialog type. 
var dialogTypeName = "System.Windows.Forms.PropertyGridInternal.GridErrorDlg"; 
var dialogType = typeof(Form).Assembly.GetType(dialogTypeName); 

// Create dialog instance. 
var dialog = (Form)Activator.CreateInstance(dialogType, new PropertyGrid()); 

// Populate relevant properties on the dialog instance. 
dialog.Text = "Sample Title"; 
dialogType.GetProperty("Details").SetValue(dialog, "Sample Details", null); 
dialogType.GetProperty("Message").SetValue(dialog, "Sample Message", null); 

// Display dialog. 
var result = dialog.ShowDialog(); 

Risultato:

Details Dialog

+1

se non voglio annullare l'opzione in questa finestra di messaggio, cosa devo fare? –

10

È necessario impostare le seguenti proprietà di Form per creare una finestra di dialogo/messaggio personalizzata.

  1. AcceptButton
  2. CancelButton
  3. FormBorderStyle = FixedDialog
  4. MaximizeBox = False
  5. MinimizeBox = False
  6. ShowIcon = False
  7. ShowInTaskBar = False
  8. StartPosition = CenterParent

Ora, utilizzare il metodo ShowDialog() per visualizzare la finestra di dialogo personalizzata.

MyDialog dialog=new MyDialog(); 
DialogResult result=dialog.ShowDialog(); 
if(result == DialogResult.OK) 
{ 
    // 
} 

Per ulteriori informazioni sulla finestra di dialogo leggere MSDN articolo - Dialog Boxes (Visual C#)

+0

Sulla base di questa risposta ho scritto il modulo personalizzato. Guarda qui: http://stackoverflow.com/a/40469355/3314922 – gneri

3

basta scrivere il proprio dialogo, non c'è un sovraccarico come si desidera mostrare metodo.

0

Si può semplicemente fare questo:

catch (Exception error) 
{ 
    throw new Exception("Error with details button! \n"+error); 
} 

Il testo in "" è "adicionar Fotografia".

Nota: questo codice funziona correttamente quando si esegue l'applicazione (.exe) durante l'esecuzione in editor, non funziona e ha senso.

This is an example of the code above

+0

Sebbene questo codice possa rispondere alla domanda, fornire un contesto aggiuntivo sul perché e/o su come questo codice risponde alla domanda migliora il suo valore a lungo termine. – ryanyuyu

1

Basato su @ risposta di AVD sopra (che ho upvoted) ho scritto quanto segue. Incollalo in un modulo che hai generato usando un modello VS e dovrebbe funzionare, magari con qualche piccola modifica.

Il mio codice:

using System; 
using System.Windows.Forms; 

namespace MessageBoxWithDetails 
{ 
    /// <summary> 
    /// A dialog-style form with optional colapsable details section 
    /// </summary> 
    public partial class MessageBoxWithDetails : Form 
    { 
     private const string DetailsFormat = "Details {0}"; 

    public MessageBoxWithDetails(string message, string title, string details = null) 
    { 
     InitializeComponent(); 

     lblMessage.Text = message; 
     this.Text = title; 

     if (details != null) 
     { 
      btnDetails.Enabled = true; 
      btnDetails.Text = DownArrow; 
      tbDetails.Text = details; 
     } 
    } 

    private string UpArrow 
    { 
     get 
     { 
      return string.Format(DetailsFormat, char.ConvertFromUtf32(0x25B4)); 
     } 
    } 

    private string DownArrow 
    { 
     get 
     { 
      return string.Format(DetailsFormat, char.ConvertFromUtf32(0x25BE)); 
     } 
    } 

    /// <summary> 
    /// Meant to give the look and feel of a regular MessageBox 
    /// </summary> 
    public static void Show(string message, string title, string details = null) 
    { 
     new MessageBoxWithDetails(message, title, details).ShowDialog(); 
    } 

    protected override void OnLoad(EventArgs e) 
    { 
     base.OnLoad(e); 

     // Change these properties now so the label is rendered so we get its real height 
     var height = lblMessage.Height; 
     SetMessageBoxHeight(height); 
    } 

    private void SetMessageBoxHeight(int heightChange) 
    { 
     this.Height = this.Height + heightChange; 
     if (this.Height < 150) 
     { 
      this.Height = 150; 
     } 
    } 

    private void btnClose_Click(object sender, EventArgs e) 
    { 
     this.Close(); 
    } 

    private void btnDetails_Click(object sender, EventArgs e) 
    { 
     // Re-anchoring the controls so they stay in their place while the form is resized 
     btnCopy.Anchor = AnchorStyles.Top; 
     btnClose.Anchor = AnchorStyles.Top; 
     btnDetails.Anchor = AnchorStyles.Top; 
     tbDetails.Anchor = AnchorStyles.Top; 

     tbDetails.Visible = !tbDetails.Visible; 
     btnCopy.Visible = !btnCopy.Visible; 

     btnDetails.Text = tbDetails.Visible ? UpArrow : DownArrow; 

     SetMessageBoxHeight(tbDetails.Visible ? tbDetails.Height + 10 : -tbDetails.Height - 10); 
    } 

    private void btnCopy_Click(object sender, EventArgs e) 
    { 
     Clipboard.SetText(tbDetails.Text); 
    } 
} 

Designer automatico generato il codice (che dovrebbe darvi un'idea riguardo a cosa mettere in forma se non si desidera incollare esso):

namespace MessageBoxWithDetails 
{ 
    partial class MessageBoxWithDetails 
    { 
     /// <summary> 
     /// Required designer variable. 
     /// </summary> 
     private System.ComponentModel.IContainer components = null; 
     /// <summary> 
     /// Clean up any resources being used. 
     /// </summary> 
     /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> 
     protected override void Dispose(bool disposing) 
     { 
      if (disposing && (components != null)) 
      { 
       components.Dispose(); 
      } 
      base.Dispose(disposing); 
     } 

     #region Windows Form Designer generated code 

     /// <summary> 
     /// Required method for Designer support - do not modify 
     /// the contents of this method with the code editor. 
     /// </summary> 
     private void InitializeComponent() 
     { 
      this.btnClose = new System.Windows.Forms.Button(); 
      this.btnDetails = new System.Windows.Forms.Button(); 
      this.btnCopy = new System.Windows.Forms.Button(); 
      this.lblMessage = new System.Windows.Forms.Label(); 
      this.tbDetails = new System.Windows.Forms.TextBox(); 
      this.SuspendLayout(); 
      // 
      // btnClose 
      // 
      this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
      | System.Windows.Forms.AnchorStyles.Right))); 
      this.btnClose.Location = new System.Drawing.Point(267, 37); 
      this.btnClose.Name = "btnClose"; 
      this.btnClose.Size = new System.Drawing.Size(75, 23); 
      this.btnClose.TabIndex = 0; 
      this.btnClose.Text = "Close"; 
      this.btnClose.UseVisualStyleBackColor = true; 
      this.btnClose.Click += new System.EventHandler(this.btnClose_Click); 
      // 
      // btnDetails 
      // 
      this.btnDetails.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
      | System.Windows.Forms.AnchorStyles.Right))); 
      this.btnDetails.Enabled = false; 
      this.btnDetails.Location = new System.Drawing.Point(12, 37); 
      this.btnDetails.Name = "btnDetails"; 
      this.btnDetails.Size = new System.Drawing.Size(75, 23); 
      this.btnDetails.TabIndex = 1; 
      this.btnDetails.Text = "Details"; 
      this.btnDetails.UseVisualStyleBackColor = true; 
      this.btnDetails.Click += new System.EventHandler(this.btnDetails_Click); 
      // 
      // btnCopy 
      // 
      this.btnCopy.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
      | System.Windows.Forms.AnchorStyles.Right))); 
      this.btnCopy.Location = new System.Drawing.Point(93, 37); 
      this.btnCopy.Name = "btnCopy"; 
      this.btnCopy.Size = new System.Drawing.Size(102, 23); 
      this.btnCopy.TabIndex = 4; 
      this.btnCopy.Text = "Copy To Clipboard"; 
      this.btnCopy.UseVisualStyleBackColor = true; 
      this.btnCopy.Visible = false; 
      this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click); 
      // 
      // lblMessage 
      // 
      this.lblMessage.AutoSize = true; 
      this.lblMessage.Location = new System.Drawing.Point(12, 9); 
      this.lblMessage.MaximumSize = new System.Drawing.Size(310, 0); 
      this.lblMessage.Name = "lblMessage"; 
      this.lblMessage.Size = new System.Drawing.Size(35, 13); 
      this.lblMessage.TabIndex = 5; 
      this.lblMessage.Text = "label1"; 
      // 
      // tbDetails 
      // 
      this.tbDetails.Anchor = System.Windows.Forms.AnchorStyles.Bottom; 
      this.tbDetails.Location = new System.Drawing.Point(12, 68); 
      this.tbDetails.MaximumSize = new System.Drawing.Size(328, 100); 
      this.tbDetails.Multiline = true; 
      this.tbDetails.Name = "tbDetails"; 
      this.tbDetails.ReadOnly = true; 
      this.tbDetails.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; 
      this.tbDetails.Size = new System.Drawing.Size(328, 100); 
      this.tbDetails.TabIndex = 6; 
      this.tbDetails.Visible = false; 
      // 
      // MessageBoxWithDetails 
      // 
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 
      this.ClientSize = new System.Drawing.Size(354, 72); 
      this.Controls.Add(this.tbDetails); 
      this.Controls.Add(this.lblMessage); 
      this.Controls.Add(this.btnCopy); 
      this.Controls.Add(this.btnDetails); 
      this.Controls.Add(this.btnClose); 
      this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; 
      this.MaximizeBox = false; 
      this.MinimizeBox = false; 
      this.Name = "MessageBoxWithDetails"; 
      this.ShowIcon = false; 
      this.ShowInTaskbar = false; 
      this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; 
      this.ResumeLayout(false); 
      this.PerformLayout(); 

     } 

     #endregion 

     private System.Windows.Forms.Button btnClose; 
     private System.Windows.Forms.Button btnDetails; 
     private System.Windows.Forms.Button btnCopy; 
     private System.Windows.Forms.Label lblMessage; 
     private System.Windows.Forms.TextBox tbDetails; 
    } 
} 
Problemi correlati