0

so because of an odd performance issue we currently need to run a windows form and force it to act like a console project. not really a problem and this is working fine while the third part looks into the performance issue.

when you do this,

Console.WriteLine("something") 

does not actually print out to the console.

Solution for that was adding the following (found on a bunch of SO posts)

[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
private static extern bool AttachConsole(int processId);

then call that method in the Main

            AttachConsole(-1);

ok this works fine, still need to see if this ends up causing the same performance issue that originally prompted us to use a windows form solution in the first place TBD.

Being that i do not want to have to copy this code into every project (Booooo), I created a custom Attribute and added that code to it.

public class FormOnConsol : Attribute
{
    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
    public static extern bool AttachConsole(int processId);

    public FormOnConsol(int processid = -1)
    {
        AttachConsole(processid);
    }
}

cant seem to figure out why that is not working when used like

    [STAThread]
    [FormOnConsol]
    static void Main()
    {
          //some fun code here
          //naturally because all code is fun =]
    }

any point in the right direction is much appreciated!

Thanks in advance!

workabyte
  • 3,496
  • 2
  • 27
  • 35

1 Answers1

3

Constructor of attribute will be activated only if you query it. See more info on this topic here: when-is-a-custom-attributes-constructor-run

P.S. It is not right to use attributes for any active actions. It should be used merely for declarative purposes.

Community
  • 1
  • 1
Igos
  • 211
  • 1
  • 3
  • Thanks for the reply, will look into it. Was kinda an excuse to make an attribute and just seemed like a non-obtrusive way to include this. happen to have a recommendation for a better way to approach this? guess i could just make a base class that does this, just seems "cleaner" to have it be an attribute. – workabyte May 27 '14 at 14:06
  • 2
    Yes, using base class is more natural way for that. – Igos May 27 '14 at 14:17