Rsge
Rsge

Reputation: 121

WinForms Startup Event not being handled

I have a Windows Forms Application in .NET 5 with Application Framework activated and the startup object set to (my) MainForm.
Using "View Application Events" in the application's properties, I auto-generated the ApplicationEvents.vb file and with the given controls auto-generated a method to do something on Startup (as I understand before even the MainForm loads) - but nothing in this method gets run, not even breakpoints are triggered.
I would assume an auto-generated sub in an auto-generated file designed for this should work and every other event handling sub does, just not Startup's.

This is my ApplicationEvents.vb (without the auto-generated comment):

Imports Microsoft.VisualBasic.ApplicationServices

Namespace My
    Partial Friend Class MyApplication
        Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
            Debug.Print("Test")
            MsgBox("Test")
        End Sub
    End Class
End Namespace
Background:

I'm trying to enable high DPI scaling for my application.
For this I've tried using the app.manifest file (opened by "View Windows Settings" in the application's properties), but no combination of tags I found in the docs worked (I'm running the required version of Windows 10 of cause). The same for the app.config file, but I expected this because it's a .NET Framework feature to use it for that.
So I landed on Application.SetHighDpiMode(HighDpiMode). This worked when put into the MainForm's Loadevent, but it only did what was intended when the form was already loaded and it was then put on a scaled up screen / the screen was scaled up while it was already loaded. If it was started on an already scaled screen, it looked jumbled.
So I figured that enabling it only on the form loading is just a bit too late and it should be run asap, so I landed on Startup.

Upvotes: 1

Views: 771

Answers (1)

Rsge
Rsge

Reputation: 121

The startup object has to be Sub Main for the Startup event to work, not MainForm (or any form at all).
(Thanks to @Hans Passant for the tip.)

If you want to change which one is the main form later on you have to do the following:

  1. Close your project in Visual Studio.
  2. Open your project's folder in explorer.
  3. In it, open folder My Project.
  4. Open Application.myapp with any text editor.
  5. Change the form between the <MainForm> tags to your (new) main forms name.
  6. Save and close.
  7. Open ApplicationDesigner.vb with any text editor.
  8. Find the following line and change YourMainFormsName to your (new) main forms name:
Protected Overrides Sub OnCreateMainForm()
    Me.MainForm = Global.YourProjectsName.YourMainFormsName
End Sub
  1. Save and close.
  2. Open your project again and start it up. The startup form should have changed.

This way you can keep the application framework and don't have to write your own Sub Main.

Upvotes: 1

Related Questions