2011-01-13 3 views
3

Я использую Addin в VS2008, C#, и мне нужны сообщения для показа (сообщения об ошибках и другие).Прокручиваемый MessageBox в C#

Я не знаю длины сообщений, поэтому я хочу использовать прокручиваемое MessageBox.

Я нашел эту статью с 2007 года: Майк Голд 30 июля 2007

http://www.c-sharpcorner.com/UploadFile/mgold/ScrollableMessageBox07292007223713PM/ScrollableMessageBox.aspx

сейчас, в 2011 году любой другой хороших компонентов ?? Я хочу оценить несколько компонентов.

Update:

другой компонент, но старше: MessageBoxExLib http://www.codeproject.com/KB/dialog/MessageBoxEx.aspx

Настраиваемый .NET WinForms Message Box. http://www.codeproject.com/KB/dialog/Custom_MessageBox.aspx

+2

Мой настраиваемый .NET Winforms Message Box не прокручивается. Он автоматически растягивается, чтобы соответствовать тексту. Поэтому, если вы отображаете сообщение об ошибке с большой трассировкой стека, поле может быть слишком большим. Если вы хотите этого избежать, вы можете отобразить сообщение об ошибке и добавить в окно сообщения пользовательскую кнопку «показать трассировку стека» и/или добавить «Скопировать трассировку стека в буфер обмена». – MaxK

ответ

2

Я только что реализовал простую форму с прокручиваемым многострочным текстовым полем, когда мне было нужно что-то похожее, чтобы показать длинные отчеты о состоянии или исключения, обнаруженные приложением. Вы можете изменить границы и т. Д., Чтобы сделать его похожим на ярлык, если хотите. Затем только новый и вызовите его метод ShowDialog или завершите его создание в некотором статичном элементе, подобном MessageBox. Насколько я знаю, команда .NET не построила ничего более гибкого, чем MessageBox.

РЕДАКТИРОВАТЬ ОТ КОММЕНТАРИЕВ:

кода, чтобы сделать окно с текстовым полем, которые можно показать, используя статический метод достаточно просто. Хотя я вообще не люблю откровенные запросы на код, я обязывать на этот раз:

public class SimpleReportViewer : Form 
{ 
    /// <summary> 
    /// Initializes a new instance of the <see cref="SimpleReportViewer"/> class. 
    /// </summary> 
    //You can remove this constructor if you don't want to use the IDE forms designer to tweak its layout. 
    public SimpleReportViewer() 
    { 
     InitializeComponent(); 
     if(!DesignMode) throw new InvalidOperationException("Default constructor is for designer use only. Use static methods instead."); 
    } 

    private SimpleReportViewer(string reportText) 
    { 
     InitializeComponent(); 
     txtReportContents.Text = reportText; 
    } 

    private SimpleReportViewer(string reportText, string reportTitle) 
    { 
     InitializeComponent(); 
     txtReportContents.Text = reportText; 
     Text = "Report Viewer: {0}".FormatWith(reportTitle); 
    } 

    /// <summary> 
    /// Shows a SimpleReportViewer with the specified text and title. 
    /// </summary> 
    /// <param name="reportText">The report text.</param> 
    /// <param name="reportTitle">The report title.</param> 
    public static void Show(string reportText, string reportTitle) 
    { 
     new SimpleReportViewer(reportText, reportTitle).Show(); 
    } 

    /// <summary> 
    /// Shows a SimpleReportViewer with the specified text, title, and parent form. 
    /// </summary> 
    /// <param name="reportText">The report text.</param> 
    /// <param name="reportTitle">The report title.</param> 
    /// <param name="owner">The owner.</param> 
    public static void Show(string reportText, string reportTitle, Form owner) 
    { 
     new SimpleReportViewer(reportText, reportTitle).Show(owner); 
    } 

    /// <summary> 
    /// Shows a SimpleReportViewer with the specified text, title, and parent form as a modal dialog that prevents focus transfer. 
    /// </summary> 
    /// <param name="reportText">The report text.</param> 
    /// <param name="reportTitle">The report title.</param> 
    /// <param name="owner">The owner.</param> 
    public static void ShowDialog(string reportText, string reportTitle, Form owner) 
    { 
     new SimpleReportViewer(reportText, reportTitle).ShowDialog(owner); 
    } 

    /// <summary> 
    /// Shows a SimpleReportViewer with the specified text and the default window title. 
    /// </summary> 
    /// <param name="reportText">The report text.</param> 
    public static void Show(string reportText) 
    { 
     new SimpleReportViewer(reportText).Show(); 
    } 

    /// <summary> 
    /// Shows a SimpleReportViewer with the specified text, the default window title, and the specified parent form. 
    /// </summary> 
    /// <param name="reportText">The report text.</param> 
    /// <param name="owner">The owner.</param> 
    public static void Show(string reportText, Form owner) 
    { 
     new SimpleReportViewer(reportText).Show(owner); 
    } 

    /// <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() 
    { 
     System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SimpleReportViewer)); 
     this.txtReportContents = new System.Windows.Forms.TextBox(); 
     this.SuspendLayout(); 
     // 
     // txtReportContents 
     // 
     this.txtReportContents.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                       | System.Windows.Forms.AnchorStyles.Left) 
                       | System.Windows.Forms.AnchorStyles.Right))); 
     this.txtReportContents.Location = new System.Drawing.Point(13, 13); 
     this.txtReportContents.Multiline = true; 
     this.txtReportContents.Name = "txtReportContents"; 
     this.txtReportContents.ReadOnly = true; 
     this.txtReportContents.ScrollBars = System.Windows.Forms.ScrollBars.Both; 
     this.txtReportContents.Size = new System.Drawing.Size(383, 227); 
     this.txtReportContents.TabIndex = 0; 
     // 
     // SimpleReportViewer 
     // 
     this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 
     this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 
     this.ClientSize = new System.Drawing.Size(408, 252); 
     this.Controls.Add(this.txtReportContents); 
     this.Icon = Properties.Resources.some_icon; 
     this.Name = "SimpleReportViewer"; 
     this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; 
     this.Text = "Report Viewer"; 
     this.ResumeLayout(false); 
     this.PerformLayout(); 

    } 

    #endregion 

    private TextBox txtReportContents; 
} 

Использование:

var message = GetSomeRidiculouslyLongMessage(); 
//assumes it's called from inside another Form 
SimpleReportViewer.ShowDialog(message, "My Message", this); 

Эта конкретная реализация также поддерживает отображение как обычный, без диалогового окна с помощью перегрузки метода Show().

+1

Вы публиковали как альтернативы codeproject? – Kiquenet

+0

Что такое "westec" ??? – rolls

+0

Westec похоже на название компании, относящееся к внутренним компонентам. Чтобы выполнить эту работу, вам нужно заменить «new Westec.CommonLib.Presentation.Controls.WestecTextBox(); с 'новым TextBox()', 'WestecTextBox' с 'TextBox', 'Westec.CommonLib.Presentation.Properties.Resources.interface_icon;' с «SystemIcons.Error» (или другой значок по вашему выбору). – Taran

6

Возьмите это один: FlexibleMessageBox – A flexible replacement for the .NET MessageBox

Это проверенный класс, который легко заменяет все ваши обычаи MessageBox.Show и позволяет получить больше возможностей в одном файле класса вы можете легко добавить в свой проект.

+1

Отказ от ответственности: автор этого ответа написал связанный код. Однако, попробовав это, это лучшее решение и гораздо лучше выглядит с лучшим интерфейсом, чем решение ниже. Было бы неплохо, если бы вы размещали его где-то, как github, который не требовал регистрации ... – Taran

+0

Было бы еще лучше, если бы он был размещен в NuGet, так как это разочаровывает необходимость скопировать + вставить код из проекта Codeplex. – csharpforevermore

+0

Спасибо! Очень признателен! – Hudson

0

Я искал прокручиваемый почтовый ящик для WPF - и тогда я нашел MaterialMessageBox, который является (на мой взгляд) красивой альтернативой FlexibleMessageBox для WPF. Вы можете скачать его из GitHub здесь: https://github.com/denpalrius/Material-Message-Box или установить его как пакет nuget внутри Visual Studio (https://www.nuget.org/packages/MaterialMessageBox/).

Единственная проблема, которую я обнаружил, что вы не можете использовать его из-за пределов основного потока, так что мое решение, которое должно было вызвать основной поток и показать сообщение оттуда: mainWindow.Dispatcher.Invoke(() => MaterialMessageBox.Show("message text"));