开发者

Console.Write is not working when executed by BackgroundWorker of .NET GUI Application

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: Console.Write in .NET GUI Applicatio开发者_运维知识库n 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?


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.


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();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜