Unhandled C # User Control Exceptions Used in the MFC Dialog

Our main application is built on MFC C ++, but we are trying to write new code in .NET and created a user control in .NET that will be used in the existing MFC dialog box.

However, when an unexpected / unhandled exception is thrown from User Control, this causes the MFC application (illegal op style) to crash and cannot be recovered.

I added

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

To the constructor of the .NET user control, but it does not seem to catch anything.

Is there a way to add an event to MFC to handle them?

Fast google did not return anything useful.

Thanks.


: , , , .NET, .

+3
4

: / ?

, . WndProc - , .

: CWinApp Exception ^. . Structured Exception Handling (SEH), / . .

+3

, MFC:

AppDomain:: CurrentDomain- > UnhandledException + = gcnew UnhandledExceptionEventHandler (& CurrentDomain_UnhandledException);

[ Application.ThreadException]

MSDN:

0

, #, , , , . ?

try/catch:

private void btnOk_Click(object sender, EventArgs e) {
    try {
        // real code here
    }
    catch (Exception ex) {
        LogException(ex);
        // do whatever you must in order to shut down the control, maybe just
    }
}

:

public static class UI
{
    public static void PerformUIAction(Control form, Action action)
    {
        PerformUIAction(form, action, (string) null);
    }

    public static void PerformUIAction(
        Control form, Action action, string message)
    {
        PerformUIAction(form, action, () => message);
    }

    public static void PerformUIAction(
        Control form, Action action, Func<string> messageHandler)
    {
        var saveCursor = form.Cursor;
        form.Cursor = Cursors.WaitCursor;
        try
        {
            action();
        }
        catch (Exception ex)
        {
            MessageBox.Show(
                messageHandler() ?? ex.Message, "Exception!",
                MessageBoxButtons.OK, MessageBoxIcon.Error,
                MessageBoxDefaultButton.Button1,
                MessageBoxOptions.DefaultDesktopOnly);
            Debug.WriteLine(ex.ToString(), "Exception");
            throw;
        }
        finally
        {
            form.Cursor = saveCursor;
        }
    }
}

:

private void _copyButton_Click(object sender, EventArgs e)
{
    UI.PerformUIAction(
        this, () =>
                  {
                  // Your code here
                  });
}
0

.NET

, ; , Application.Run. Application.Run ?

- MFC .NET:

Application.SetUnhandledExceptionMode(System.Windows.Forms.UnhandledExceptionMode.CatchException);
Application.ThreadException += ...;

, ThreadException.

0

Source: https://habr.com/ru/post/1713606/


All Articles