tags:

views:

43

answers:

2

I've a (C#).NET GUI application. Where I need console for displaying some output. The code that (is writing to console) contains Console.WriteLine statements is executed by the BackgroundWorker & not the main thread.

Some one suggested,here: http://stackoverflow.com/questions/3385097/console-write-in-net-gui-application/3385142 that making your application typeConsole Application instead of "Windows Application" will do the job. But this is only working when the Main Thread (GUI thread) is writing to console. More over, I don't need Console to be displayed when application starts. I only want it when background worker begins its work and when its finished, I want console to disappear.

How can display console as required?

+2  A: 

I think you might want to keep your app as a WinForms app and then use AllocConsole and FreeConsole to create and remove the console as needed.

Since you only want to use it from the worker thread, I think it might work if you create it in the worker thread.

Please note, I haven't tried the above, so I'm not sure if it would work or not.

ho1
I've tried it. It worked!
claws
A: 

Add this code to your class:

    [DllImport("kernel32.dll")]
    static extern bool AllocConsole();
    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
    static extern bool FreeConsole();

Now, In your backgroundWorker.

    private void backgroundWorker1_DoWork(Object obj, DoWorkEventArgs e)
    {
        AllocConsole();
        // do the task of your background worker here here
        FreeConsole();
    }
claws