Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Main from being auto-generated in WPF?

Tags:

wpf

I'm trying to make a single instance WPF application using the hints on:

What is the correct way to create a single-instance application?

This ultimately requires changes to Main(). In WPF, Main() seems to be auto-generated. I'd rather not modify autogenerated code. Is there a way to suppress Main from being auto-generated?

(alternatively, if you know of a better single app instance pattern for WPF that doesn't rely on modifying auto-generated code, please suggest it)

like image 487
jglouie Avatar asked Feb 29 '12 18:02

jglouie


3 Answers

From the blog: http://bengribaudo.com/blog/2010/08/26/136/wpf-where-is-your-static-main-method

The following two methods will avoid the duplicate Main collision:

  1. Tell the compiler that your static Main() method should be the execution entry point—Set your project’s “Startup object” setting to the class containing your static Main() method (right-click on the project in Solution Explorer, choose “Properties,” then look for the “Startup object” setting under the “Application” tab). (This was also mentioned by Bahri Gungor)

  2. Turn off auto-generation of App.g.cs’s static Main() method—In Solution Explorer, right click on App.xaml, choose “Properties,” then change the “Build Action” from “ApplicationDefinition” to “Page”.

like image 153
jglouie Avatar answered Nov 15 '22 11:11

jglouie


Actually, in a default WPF project, the application startup object is the App class (code-behind for app.xaml).

You can write your own class, create the startup code however you like, and start your application like this:

public class Startup
{
    [STAThread]
    public static void Main(string[] args)
    {
        // Check for existing instance (mutex or w/e) here

        //
        App app = new App();
        app.Run();
    }
}

You can change the startup object in your project file.

like image 40
Bahri Gungor Avatar answered Nov 15 '22 11:11

Bahri Gungor


I wouldn't use the mutex approach for creating a single instance WPF app. I would use the answer described here - https://stackoverflow.com/a/19326/248164.

This is also the approach described in Pro WPF in C# 2010.

like image 21
devdigital Avatar answered Nov 15 '22 10:11

devdigital