我正在尝试将控制台的文本颜色设置为给定颜色,打印一行(或更多行),然后将配色方案更改回原来的颜色。这是我所拥有的:
Function SetConsoleTextColor(NewColor As UInt16) As UInt16
Declare Function SetConsoleTextAttribute Lib "Kernel32" (hConsole As Integer, attribs As UInt16) As Boolean
Declare Function GetStdHandle Lib "Kernel32" (hIOStreamType As Integer) As Integer
Declare Function GetConsoleScreenBufferInfo Lib "Kernel32" (hConsole As Integer, ByRef buffinfo As CONSOLE_SCREEN_BUFFER_INFO) As Boolean
Declare Sub CloseHandle Lib "Kernel32" (HWND As Integer)
Const STD_OUTPUT_HANDLE = -12
Dim conHandle As Integer = GetStdHandle(STD_OUTPUT_HANDLE)
Dim buffInfo As CONSOLE_SCREEN_BUFFER_INFO //A structure defined elsewhere
If GetConsoleScreenBufferInfo(conHandle, buffInfo) Then
Call SetConsoleTextAttribute(conHandle, NewColor)
CloseHandle(conHandle)
Return buffInfo.Attribute
Else
Return 0
End If
End Function
这在第一次通话时效果很好。更改控制台上新输出的文本颜色并返回以前的属性。但是,当我第二次调用它来重置属性时,GetStdHandle
返回的句柄与前一次调用相同,但现在无效(因为我关闭了它。)
当然,当我尝试使用句柄时,这会导致错误。如果我创建conHandle
一个静态变量并且仅在等于零时调用GetStdHandle
(conHandle
RealBasic 中新数字变量的默认值),它可以正常工作。
我总是被告知要自己清理。我应该让这个把手打开吗?