Vlad, for a programmer, there is not such thing as "crashing". You should use debugger properly and, in order to post a correct Question for a CodeProject, learn how to dump exception information.
Spotting this particular problem based on your posted code is a bit tedious and boring. We could do little better. Let me help you a bit with
System.Windows.Forms
specific exception handling feature which many developers miss; so it will help you in future as well (and please forgive me if you already know that). Most likely, all your problem unfolds in you UI thread. This is what you have to do first.
In your entry point function (usually called
Program.Main
), add the following line (assuming "
using System.Windows.Forms;
"):
[System.STAThread]
static void Main() {
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
}
Add some handler of the special
Application
event fired on exception inside of main loop if
Application.Run
. This code should be called before you show your main form, as soon as possible, for example, in its constructor:
Application.ThreadException += delegate(
object sender,
System.Threading.ThreadExceptionEventArgs eventArgs) {
System.Windows.Forms.MessageBox.Show(
string.Format(
"{0}: \n\n{1}",
eventArgs.Exception.GetType().Name,
eventArgs.Exception.Message),
string.Format(" {0}: Error", Application.ProductName),
MessageBoxButtons.OK, MessageBoxIcon.Error);
};
If your Framework version is 3.5 or later, lambda form is more convenient:
Application.ThreadException += (sender, eventArgs) => {
};
This will show all your exceptions in UI thread without termination of the application, you also can effectively use debugger break point in this function.
[EDIT]
Additionally or alternatively, handle the events
System.AppDomain.UnhandledException
and
System.AppDomain.FirstChanceException
.
My credit to Espen Harlinn for the idea.
[END EDIT]
If it does not provide enough information, add detailed dump: exception stack (first thing to do) and possibly all inner exceptions, recursively. If you want help from CodeProject, save this dump in file and post its content in your Question (please, try to format nicely!).
If your problem is still not resolved, ask follow-up questions, but please not post it as an Answer (
important!); use "Improve question" or "Add comment".
By the way, I did not understand why you use P/Invoke, that is, why pure .NET API was not enough?
—SA