I would like to override orignal main method in WPF.
I want add content at the beginnig of the origina main method. How to do it?
It seems that it has to be done in App.xaml.cs
file, but still don't know how to achieve it.
I would like to override orignal main method in WPF.
I want add content at the beginnig of the origina main method. How to do it?
It seems that it has to be done in App.xaml.cs
file, but still don't know how to achieve it.
I don't believe you can, directly. The designer introduces its own Main
method.
What you can do is create your own separate class with a Main
method, which in turn calls App.Main
when you want to:
using System;
namespace AppWithCustomMain
{
class CustomMain
{
[STAThread]
static void Main()
{
Console.WriteLine("CustomMain!");
App.Main();
}
}
}
Then set the "startup object" build setting in your project properties to CustomMain
, and it should call your Main
method first, which in turn calls into App.Main
.
This is assuming you really need to get in before anything else, however. Normally you'd just either subscribe to the Application.Startup
event, or override Application.OnStartup
within your Application
subclass.
You can introduce a new Run()
-method in your App
class (yes, you're right - it has to be done inside the App.xaml.cs
- , make your stuff and then call the base implementation:
public partial class App : Application
{
public new void Run()
{
// Do your stuff here
// Call the base method
base.Run();
}
}
You shouldn't really override the main method of the application, if you want to call a specific method when your application starts up, you can override the OnStartup
method of the App
class (file App.xaml.cs
).
Here's an example:
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// Your code here
}
}