Author Topic: Save and Restore Console FG and BG colors  (Read 383 times)

MrBcx

  • Administrator
  • Hero Member
  • *****
  • Posts: 786
    • View Profile
Save and Restore Console FG and BG colors
« on: July 13, 2020, 05:51:53 PM »
I wrote these but seldom use them but they do come in handy if you like
making console mode apps.  When using the COLOR statement, it is easy to overlook
the benefit of restoring the USER's default foreground and background text colors.

The two SUBs below can help.  Call GetColors() at the start of your app before you
change any colors.  Then whenever you want to restore the user's colors, simply call
PutColors().

You should only need to call GetColors() one time but you can call PutColors()
as many times as you want.


Note:  These have been tested to work even when the user has set custom
BG and FG colors set through the console's properties.


Code: [Select]
'**********************************************************************
' For Console Mode Screen Writing
' Save the user's FG and BG colors before you use the COLOR statement.
' Use GetColors() at the start of your program and use PutColors()
' after each COLOR statement you use, to restore the users colors.
'**********************************************************************

SUB GetColors()
  GLOBAL SavedColors
  LOCAL info AS CONSOLE_SCREEN_BUFFER_INFO
  IF NOT GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info) THEN
   SavedColors = 7  ' Something went wrong, so we'll set the default colors (7,0)
  ELSE
    SavedColors = info.wAttributes
  END IF
END SUB



SUB PutColors
  IF SavedColors = 0 THEN
    COLOR 7,0
  ELSE
    SetConsoleTextAttribute (GetStdHandle (STD_OUTPUT_HANDLE),SavedColors) ' restore user's colors
  END IF
END SUB

« Last Edit: July 13, 2020, 07:26:25 PM by MrBcx »