Is there any possible way to automatically append all strings/etc to a textbox(or other form) of my choice? Right now in-order to do that in any class outside of the Main class, I have to route it into it and then use the Main class to post it.
Clarification(CHANGED): I am no longer looking to just handle exceptions. I really just want to pass a string/text from 开发者_运维百科anywhere in my program without having to pass it to the MainWindow.
namespace MyProgram
{
public partial class MainWindow : Window
{
Main goes here...
}
}
namespace People
{
public class Worker
{
public void printToLog()
{
textBoxErrorlog.AppendText("Message....");
}
}
}
The code above won't work. I would have to return the string to the MainWindow class and append it from there (bc textBoxErrorlog doesn't exist in Worker). I would like to skip that step and just post it from the Worker class.
Your question is pretty vague. But I have a feeling you'll find these events interesting/useful:
Application.ThreadException
AppDomain.CurrentDomain.UnhandledException
EDIT after your added code:
Generally speaking it's bad to catch Exception
. In your case I would recommend hooking into AppDomain.CurrentDomain.UnhandledException
and in that handler append to the MainWindow's exception log textbox.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (!e.IsTerminating)
{
MainWindow mw = GetRefToTheMainWindowSomehow();
mw.AppendException(e.ExceptionObject);
}
}
And in MainWindow:
internal delegate void AppendExceptionDelegate(Exception e);
public void AppendException(Exception e)
{
if (this.InvokeRequired)
{
this.Invoke(new AppendExceptionDelegate(AppendException), new[] { e });
}
else
{
this._textBox.Text += e.Message;
}
}
You could create a custom appender for Log4Net and have it do it. Other than that you need to catch the exceptions and marshall them back to the UI thread.
You could leverage wiring up the UnhandledException
event from the AppDomain
and routing all unhandled exceptions to whatever you like.
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += (sender, args) => { /* Write To Wherever */ };
I would recommend fleshing that out to using a real handler etc, but it gives you an idea.
精彩评论