Note: I don't do .NET programming regularly. Normally I do native/MFC, so I'm a bit lost as how to do this properly in the context of C#.
We're displaying .NET control in the context of a native MFC application. That means the GUI thread is a native thread calling into the WndProc of the .NET control. (Well, at least as far as I can tell.)
Obviously, we do not want to throw exceptions from our (GUI) event handlers, as there is no proper handler down the call stack that would catch them.
As far as I can tell, the solution(s) with AppDomain
/ UnhandledExceptionEventHandler
do not make sense in a native MFC application. (Please correct me if I'm wrong.)
So back to the question: How can I avoid having to add a try/catch block to each event handler of the C# control code? Is there some place (System.Forms...Control.WndProc maybe?) where I can catch all .NET exceptions and just display an error dialog to the user?
You can reduce boilerplate code by using a functional approach. Write a function like this:
And reuse it in every of your GUI event handlers:
or
This might need some additional work to get the sender/EventArgs parameters the way you want them, but you should get the idea.