douglasg14b / BetterConsoleTables

Faster, colorable, more configurable, and more robust console colors & tables for C# console applications
GNU Lesser General Public License v3.0
92 stars 16 forks source link

TableConfiguration.ConsoleAvailable static property #6

Closed bchavez closed 5 years ago

bchavez commented 5 years ago

Turns out, detecting if your code has a console attached is a non-trivial process. :rofl: at Microsoft.

The only reliable way I could find is to actually call the underlying Console.WindowHeight/Width API and wait for it to throw an exception to test if a console is present or not.

https://stackoverflow.com/questions/6408588/how-to-tell-if-there-is-a-console

https://stackoverflow.com/questions/1188658/how-can-a-c-sharp-windows-console-application-tell-if-it-is-run-interactively

Environment.UserInteractive is true in LINQPad and in a standard Console Application.

Structured error handling (SHE) is the only reliably way to check if the console is attached or not; but using SHE is a performance killer.

So, I mostly opted for a global flag. The reason it's global was mostly because TableConfiguration.Unicode() is static and set defaults where Console.OutputEncoding is getting set too; which throws again and so the flag can't be an instance flag during TableConfiguration construction.

I guess it's okay since it's kind of an obscure scenario with how I'm using this; but it does work pretty well now in LINQPad. :+1:

douglasg14b commented 5 years ago

Looks good.

I'll probably add in some error handling anyways and mark the global, so only one exception needs to be thrown.

Thanks!