6

Is it possible to execute any user-provided code before the .NET Main method?

It would be acceptable if the code had to be unmanaged.

The reason for asking is that this might be a way to solve the problem of calling SetCurrentProcessExplicitAppUserModelID before any UI elements are displayed (as mentioned in Grouping separate processes in the Windows Taskbar)

Community
  • 1
  • 1
David Gardiner
  • 16,892
  • 20
  • 80
  • 117

2 Answers2

13

In C# you can add a static constructor to the class which contains the main method. The code in the static constructor will be executed before main.

Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
  • That certainly does execute before Main, though it doesn't seem resolve the issue of calling SetCurrentProcessExplicitAppUserModelID. Maybe the problem is it's a Console app – David Gardiner Dec 19 '12 at 05:40
  • Yes, changing to a Windows app instead of Console solved my other problem. – David Gardiner Dec 19 '12 at 23:24
2

A static constructor will execute before Main, but only if the class is actually being referenced by something. Eg:

class ClassWStaticCon
{
    static ClassWStaticCon()
    {
        Console.WriteLine("Hello world!");
    }
}

...
static void Main(string[] args)
{
    Console.WriteLine("Hello main.");
}

Will print:

Hello main.

class ClassWStaticCon
{
    public static int SomeField;
    static ClassWStaticCon()
    {
        Console.WriteLine("Hello world!");
    }
}

...
static void Main(string[] args)
{
    ClassWStaticCon.SomeField = 0;
    Console.WriteLine("Hello main.");
}

Will print:

Hello world! Hello main.

If you want to control the order of execution then use a Queue of Action delegates http://msdn.microsoft.com/en-us/library/018hxwa8.aspx in a single static 'initialize all pre main stuff' class.

Alec Thilenius
  • 524
  • 5
  • 12