No Main() in WPF?
Asked Answered
W

8

147

I am a beginner when it comes to programming but I was sure that one of the universal rules was that a program starts with Main(). I do not see one when I create a WPF project. Is Main() simply named something differently in WPF?

Wellfound answered 22/4, 2010 at 21:32 Comment(2)
You can get the equivalent functionality by overriding OnStartup in App.xaml.cs. StartupEventArgs.Args contains the commandline arguments.Dishcloth
@Foole, no, you can not, see this question.Drooff
I
80

It is generated during build, but you can provide your own (disambiguating it in project-properties as necessary). Look in obj/debug for an app file; I have (courtesy of "C# 2010 Express") App.g.i.cs with:

namespace WpfApplication1 {


    /// <summary>
    /// App
    /// </summary>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
    public partial class App : System.Windows.Application {

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {

            #line 4 "..\..\..\App.xaml"
            this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);

            #line default
            #line hidden
        }

        /// <summary>
        /// Application Entry Point.
        /// </summary>
        [System.STAThreadAttribute()]
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public static void Main() {
            WpfApplication1.App app = new WpfApplication1.App();
            app.InitializeComponent();
            app.Run();
        }
    }
}
Isomerism answered 22/4, 2010 at 21:37 Comment(2)
The same thing exists in App.g.cs, as well. But I tried to add to Main() and every time I would rebuild my project, it would revert to what you have, here. Tried to create my own in another class, but Project Properties only finds MyProject.App, not the other class, so can't redirect it.Soiree
Alternatively, open App.xaml.cs in visual studio. Use the navigation bar > Method drop down list > select Main (greyed out). This takes you to App.g.i.cs.Sthilaire
C
153

The Main() method is created automatically. If you want to provide your own you have to (tested in VS2013, VS2017 and VS2019):

  • Right-click App.xaml in the solution explorer, select Properties
  • Change 'Build Action' to 'Page' (initial value is 'ApplicationDefinition')

Then just add a Main() method to App.xaml.cs. It could be like this:

[STAThread]
public static void Main()
{
    var application = new App();
    application.InitializeComponent();
    application.Run();
}
Cabin answered 12/11, 2014 at 15:22 Comment(7)
[STAThread] sets the COM threading model for your application. Usually you just set it to STA and don't have to worry what it does exactly. In case you are interested, check out msdn.microsoft.com/de-de/library/…Cabin
Don't do this! This will permanently break StaticResources defined in App.xaml in Styles in the Designer for the whole project.Larsen
App.xaml disappears after trying to click Page in Build ActionAngularity
What IDE and project type are you using @user3625699?Cabin
@AndreasKahler An error has occurred while saving the edited properties listed below: Build Action One or more values are invalid. Cannot add 'App.xaml' to the project, because the path is explicitly excluded from the project (C:\Program Files\dotnet\sdk\6.0.100-preview.4.21255.9\Sdks\Microsoft.NET.Sdk.WindowsDesktop\targets\Microsoft.NET.Sdk.WindowsDesktop.targets (88,5)). And then App.xaml disappears. I am using casual WPF application template on .NET 6 preview 4 and Visual Studio 16.11 preview 1Angularity
@Angularity You are not the only one with this problem. google for "because the path is explicitly excluded from the project". Not sure if there is an easy solution though. Please let us know if you find one! ThxCabin
@AndreasKahler yes there is a solution for having Program.cs as startup object in a WPF application. 1. add Program.cs class 2. add the code in this answer to Program.cs 3. in project properties, choose ProjectName.Program as Startup objectAngularity
I
80

It is generated during build, but you can provide your own (disambiguating it in project-properties as necessary). Look in obj/debug for an app file; I have (courtesy of "C# 2010 Express") App.g.i.cs with:

namespace WpfApplication1 {


    /// <summary>
    /// App
    /// </summary>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
    public partial class App : System.Windows.Application {

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {

            #line 4 "..\..\..\App.xaml"
            this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);

            #line default
            #line hidden
        }

        /// <summary>
        /// Application Entry Point.
        /// </summary>
        [System.STAThreadAttribute()]
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public static void Main() {
            WpfApplication1.App app = new WpfApplication1.App();
            app.InitializeComponent();
            app.Run();
        }
    }
}
Isomerism answered 22/4, 2010 at 21:37 Comment(2)
The same thing exists in App.g.cs, as well. But I tried to add to Main() and every time I would rebuild my project, it would revert to what you have, here. Tried to create my own in another class, but Project Properties only finds MyProject.App, not the other class, so can't redirect it.Soiree
Alternatively, open App.xaml.cs in visual studio. Use the navigation bar > Method drop down list > select Main (greyed out). This takes you to App.g.i.cs.Sthilaire
H
17

Main() is automatically provided by the CLR and the WPF.

The C# compiler takes a command-line switch /m which specifies the type that contains the implementation of Main(). By convention, if no startup object is explicitly specified, the CLR will lookup any class that has a static Main() method and will call it. (As @Marc Gravel pointed out in his comment)

In the case of WPF, the Main() is automatically generated when App.xaml is built and the /m switch is specified to make the C# compiler use that class as entry point. If you look at the project properties however, you'll find there's a setting for you to choose the startup object. So if you want, you can provide your own class that implements Main().

Note that this will put the responsibility on you to create the Application instance and call its Run() method to ensure that the WPF infrastructure is started properly.

Homiletic answered 22/4, 2010 at 21:42 Comment(3)
Actually, without /m it doesn't care what the type is called; if you aren't explicit it just tries to find any suitable Main method, and complains if it finds 0 or more than one. As an example, the "Hello World" sample in the language spec (§1.1) uses Hello as the type name.Isomerism
To be pedantic: it's not really accurate to say that main() is provided by the CLR (the runtime), it's really the compiler that generates it.Diley
Added my +1 for reminding the audience they will have to add in their own Application instance (i.e. MyApp.App app = new MyApp.App();) and call .Run() on it, like the previous Main() would have. Good call. Also, would have to add app.InitializeComponent(); before app.Run(), and fortunately for us, the original InitializeComponent() method is still there (seen in App.g.cs, so no need to add that one back!).Soiree
F
10

Main() is generated during compilation. You can find it in App.g.cs (in obj/{Debug,Release} folder).

Filamentous answered 22/4, 2010 at 21:36 Comment(0)
I
6

main() is a standard entry point for an application, but all applications are structured that way. In a XAML project, the App.XAML file specifies the entry point where it says StartupUri="MainWindow.xaml".

As it is stated by others, the actual main function is generated based on the contents of the XAML files in the project.

Idiocrasy answered 22/4, 2010 at 21:39 Comment(0)
D
3

In case you removed default App.xaml and MinWindow.xaml, better to edit .csproj After adding App.xaml manually, your .csproj will be:

<Page Include ="App.xaml">
       <DependentUpon>MSBuild:Compile</DependentUpon>
       <SubType>Code</SubType>
</Page>

Change this to:

<ApplicationDefinition Include="App.xaml">
    <Generator>MSBuild:Compile</Generator>
    <SubType>Designer</SubType>
</ApplicationDefinition>
Deangelis answered 16/9, 2018 at 23:48 Comment(1)
In my case a .NET Framework 4.8 that gets data from an ancient Outlook .pst file; on top of this I want to display this data with a WPF UI; so, I had to add System.Xaml, PresentationCore and PresentationFramework and delete Program.cs; the error message "CS5001 Program does not contain a static 'Main' method suitable for an entry point" appeared after. Your advice solved. Exactly what I needed! Thanks a lot.Tannic
J
1

I copied files that wouldn't load in another project that was without a mainwindow into a new one and got this error.

For me it took doing the opposite approach to Andreas Kahler to fix:

After making a window file and setting the startup uri to this file i switched Page to ApplicationDefinition of App.xaml 'Build Action' property.

Jester answered 14/8, 2017 at 10:18 Comment(0)
C
0

To clear this is error, do the following steps:

  • Right-click on App.Xaml
  • Properties > Change Build Action
  • From Page to > ApplicationDefinition
  • Build the solution and run

It will work fine - refer to this screenshot:

enter image description here

Chipman answered 25/8, 2023 at 11:50 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.