Converting a Console Application into a GUI that u

2019-09-09 19:30发布

I am converting a console application into a Windows Forms Application and a DLL. The Windows Forms Application uses a BackgroundWorker to have the DLL perform a computationally heavy task.

Left over from the console application, the DLL is still littered with Console.WriteLine() statements. I would like to direct what used to be printed to the console into a TextBox in the Windows Form. Ideally, I would like to hook a stream from the DLL up to the text box during form initialization and be done with it. I am concerned that this might not be thread safe with the BackgroundWorker.

The best approach I have found is to change Console.WriteLine() to Trace.WriteLine() in the DLL and then follow the approach at Trace listener to write to a text box (WPF application) but I still have concerns with the BackgroundWorker and am not too keen on appending text to an existing string (there is a lot of text and IMO strings aren't meant/optimized to have lots of text concatenated on them).

What is the best way to print the old console output to the text box that will be safe with a BackgroundWorker?

1条回答
够拽才男人
2楼-- · 2019-09-09 19:50

The following blog post may be what you're looking for:

http://saezndaree.wordpress.com/2009/03/29/how-to-redirect-the-consoles-output-to-a-textbox-in-c/

I think it describes exactly what you're asking for. Basically it uses Console.SetOut to redirect the console output to a stream writer of your own. Read the comments below the post for some additional information on handling thread issues.

查看更多
登录 后发表回答