I'm pretty new to C#, and I'm quite stuck on the following problem.
I would like to add to my application a Windows.Form (singleton) on
which I could display a message of one of the following type :
Exception, Error, Warning, Infos (with differents colors, etc).
I would like to use it like the Console.WriteLi ne("My Message"); on
everywhere in my application.
Something like that :
Expand|Select|Wrap|Line Numbers
- using MyApp.Tools;
- //popup (if not already displayed) and display the error
- LogViewer.WriteLine(MessageType.Error, "Something bad happenend");
I already tried many things but I always have problems ("Windows Handle
Already Exists", form not refreshing (aka no messages loop), form not
displaying, etc.)
Sorry but I'm out of ideas. So if any one is ready to give me a very
useful help it would be really appreciated !
Here is my test class, lot's of things are commented because I made a
lot's of test.
Main questions and remarks are :
- Is the delegate way of doing ok ?
- Since this code can be called before the main Application.Run (new
MainForm) should I call an Application.Run () for this form ?
- How to cleanly prevent the component of the form not to be released
when closing the form
Ok here we go :
using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;
using System.IO;
namespace Tools
{
/// <summary>
/// A singleton to display message in a windows form
/// </summary>
public class LogViewer : System.Windows. Forms.Form
{
//a delegate to update the rich text box from everywhere (another
thread)
private delegate void UpdateLogRtb(Me ssageType _Type, string _Text);
public enum MessageType
{
Info,
Error,
Exception
}
/// <summary>
/// Required designer variable.
/// </summary>
///
//common to all instances
private static bool m_IsDisplayed;
static private int m_CurrentLine;
private static System.Windows. Forms.RichTextB ox richTextBox = new
RichTextBox();
private static System.Windows. Forms.Button btnSaveAs = new
System.Windows. Forms.Button();
private static System.Windows. Forms.Button btnClearLog = new
System.Windows. Forms.Button();
private static System.Threadin g.Thread m_UiThread;
static private LogViewer m_LogViewer = new LogViewer();
static LogViewer()
{
InitializeCompo nent();
m_IsDisplayed = false;
m_CurrentLine = 0;
}
/// <summary>
/// Private constructor, singleton
/// </summary>
private LogViewer()
{
//new thread ready to start
//m_UiThread = new System.Threadin g.Thread(new
System.Threadin g.ThreadStart(U IThread));
//m_UiThread.Star t();
}
//private void UIThread()
//{
// Application.Run (Instance);
//}
public static LogViewer Instance
{
get
{
return m_LogViewer;
}
}
public static void UpdateLog(Messa geType _Type, string _Text)
{
if ( Instance.Invoke Required )
{
UpdateLogRtb delUpdate = new UpdateLogRtb(Up dateLog);
Instance.BeginI nvoke(delUpdate , new object[]{_Type, _Text});
}
else
{
lock(richTextBo x)
{
if(!m_IsDisplay ed)
{
Instance.Show() ;
m_IsDisplayed = true;
}
Instance.SetCol or(_Type);
richTextBox.App endText(_Text);
}
}
}
void SetColor(Messag eType _Type)
{
switch(_Type)
{
case MessageType.Err or : richTextBox.Sel ectionColor =
System.Drawing. Color.Fuchsia;
break;
case MessageType.Exc eption : richTextBox.Sel ectionColor =
System.Drawing. Color.Red;
break;
case MessageType.Inf o : richTextBox.Sel ectionColor =
System.Drawing. Color.Blue;
break;
}
}
public static void WriteLine(Messa geType _Type ,string _Text,
object[] _Parameters)
{
IEnumerator iter = _Parameters.Get Enumerator();
Write(_Type, "[" + DateTime.Now.To ShortDateString () + " " +
DateTime.Now.To LongTimeString( ) + "] "+ _Text + " ");
while(iter.Move Next())
{
Write(_Type, iter.Current.To String());
Write(_Type, " ");
}
Write(_Type, "\n");
}
public static void WriteLine(Messa geType _Type ,string _Text, object
_Parameter)
{
Write(_Type, "[" + DateTime.Now.To ShortDateString () + " " +
DateTime.Now.To LongTimeString( ) + "] "+ _Text + " ");
Write(_Type, _Parameter.ToSt ring());
Write(_Type,"\n ");
}
public static void WriteLine(Messa geType _Type, string _Text)
{
Write(_Type, "[" + DateTime.Now.To ShortDateString () + " " +
DateTime.Now.To LongTimeString( ) + "] "+ _Text + " ");
Write(_Type,"\n ");
m_CurrentLine++ ;
}
public static void Write(MessageTy pe _Type, string _Text)
{
UpdateLog(_Type , _Text);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
m_IsDisplayed = false;
}
#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 static void InitializeCompo nent()
{
Instance.Suspen dLayout();
//
// richTextBox
//
richTextBox.Cur sor = System.Windows. Forms.Cursors.A rrow;
richTextBox.Loc ation = new System.Drawing. Point(0, 0);
richTextBox.Nam e = "richTextBo x";
richTextBox.Rea dOnly = true;
richTextBox.Siz e = new System.Drawing. Size(640, 250 );
richTextBox.Tab Index = 0;
richTextBox.Tex t = "";
richTextBox.Wor dWrap = false;
//
// btnSaveAs
//
btnSaveAs.Locat ion = new System.Drawing. Point(446, 254);
btnSaveAs.Name = "btnSaveAs" ;
btnSaveAs.Size = new System.Drawing. Size(89, 23);
btnSaveAs.TabIn dex = 1;
btnSaveAs.Text = "Save as...";
btnSaveAs.Click += new System.EventHan dler(btnSaveAs_ Click);
//
// btnClearLog
//
btnClearLog.Loc ation = new System.Drawing. Point(538, 254);
btnClearLog.Nam e = "btnClearLo g";
btnClearLog.Siz e = new System.Drawing. Size(100, 23);
btnClearLog.Tab Index = 2;
btnClearLog.Tex t = "Clear Log";
btnClearLog.Cli ck += new System.EventHan dler(btnClearLo g_Click);
//
// LogViewer
//
//m_LogViewer.Aut oScaleBaseSize = new System.Drawing. Size(5, 13);
Instance.Client Size = new System.Drawing. Size(640, 280);
Instance.Contro ls.Add(btnClear Log);
Instance.Contro ls.Add(btnSaveA s);
Instance.Contro ls.Add(richText Box);
Instance.FormBo rderStyle =
System.Windows. Forms.FormBorde rStyle.FixedToo lWindow;
Instance.Name = "LogViewer" ;
Instance.Text = "Events viewer";
Instance.Closin g += new
System.Componen tModel.CancelEv entHandler(LogV iewer_Closing);
Instance.Resume Layout(false);
}
#endregion
private static void LogViewer_Closi ng(object sender,
System.Componen tModel.CancelEv entArgs e)
{
Instance.Hide() ;
}
private static void btnSaveAs_Click (object sender, System.EventArg s
e)
{
SaveFileDialog saveFile = new SaveFileDialog( );
saveFile.FileNa me = "QueueMeEvents. log";
if (saveFile.ShowD ialog() != DialogResult.Ca ncel)
{
StreamWriter mySaveFile = File.CreateText (@saveFile.File Name);
mySaveFile.Auto Flush = true;
mySaveFile.Writ e(richTextBox.T ext);
mySaveFile.Clos e();
}
}
private static void btnClearLog_Cli ck(object sender, System.EventArg s
e)
{
richTextBox.Cle ar();
m_CurrentLine = 0;
}
// protected override void OnPaint(PaintEv entArgs e)
// {
// base.OnPaint (e);
// Application.DoE vents();
// Invalidate();
// System.Threadin g.Thread.Sleep( 100);
// }
}
}
Thanks !