MessageBox.Show on Form_Load?

Peter Volz 1,295 Reputation points
2023-09-25T21:31:32.22+00:00

Hello

My question is about .net framework 4.0 WinForms apps.

Is displaying a MessageBox.Show on main form's Load event bad?

Can cause any problems in exceptional cases?

2 conditions I use it are if min os req is not met a message box is shown to notify and then end the app

or if some less serious conditions are not met show a message box (question) and ask use to continue or end the app?

Because sometimes I get such remote reports:

System.InvalidOperationException: Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at MessageBox...

Developer technologies VB
Developer technologies C#
{count} votes

Accepted answer
  1. RLWA32 49,536 Reputation points
    2023-09-26T11:59:39.64+00:00

    If the real issue is that your application is running in a non-interactive environment then moving the message box from the Load event to the Startup event will not solve your problem.

    In the Startup event you should check the Environment.UserInteractive Property. If it is false then you cannot display a message box or a Form successfully. You should use an alternate method to provide user feedback such as writing to the Application Event log and/or to a file.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2023-09-26T02:40:34.7166667+00:00

    Hi @Peter Volz ,

    Click View Application Events in project properties.

    Then handle the startup event.

        Partial Friend Class MyApplication
            Private Sub a() Handles Me.Startup
                MessageBox.Show("Startup")
            End Sub
        End Class
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.