Custom Main Method in WPF Applications

To run a custom Main Method in a WPF Application you can do the following steps:

  • Set the Build Action of App.xaml to Page
  • Create a custom Application class
    Example:
namespace WpfCustomMainMethod 
{ 
     using System.Threading; 
     using System.Windows; 

     public class Program : Application 
     { 
          [System.STAThreadAttribute()] 
          static void Main() 
          { 
               var app = new Program(); 
               app.InitializeComponent(); 
               app.MainWindow = new AppWindow(); 
               app.Run(); 
          } 

          public void InitializeComponent() 
          {
               this.Startup += ProgramStartup; 
          } 

          void ProgramStartup(object sender, StartupEventArgs e) 
          { 
               var splash = new Splash {Topmost = true}; 
               splash.Show(); 
               Thread.Sleep(4000); 
               MainWindow.Show(); 
               Thread.Sleep(1500); 
               splash.Close(); 
          } 
     } 
}
  • Change the Startup Object from the Project to your new Application class
  • Edit the Project File and add the following line of code right after "</ProjectTypeGuids>":
<DesignTime Condition="'$(SolutionPath)'!='' AND Exists('$(SolutionPath)')">true</DesignTime>
  • Change the existing lines of the ApplicationDefinition block to this:
<ApplicationDefinition Condition="'$(DesignTime)'=='true' AND 
'$(BuildingInsideVisualStudio)'!='true' AND
'$(BuildingInsideExpressionBlend)'!='true'" Include="App.xaml"> <Generator>MSBuild:Compile</Generator> <SubType>Designer</SubType> </ApplicationDefinition>

Demo Project:
WpfCustomMainMethod.zip (11.54 kb)

This How-To is based on the following blogs:
http://www.infosysblogs.com/microsoft/2008/09/how_to_write_custom_main_metho.html
http://blogs.msdn.com/expression/archive/2008/04/09/creating-a-wpf-blend-project-that-loads-resources-in-code.aspx
http://learnwpf.com/Posts/Post.aspx?postId=a5643949-ab80-47f9-93c8-f5e8e5782d34

Kommentare sind geschlossen

Tags