第二次调用 GetStdHandle 返回“无效”句柄

And*_*ert 2 winapi realbasic windows-console

我试图将控制台的文本颜色设置为给定颜色,打印一行(或多行),然后将颜色方案更改回原来的颜色。这是我所拥有的:

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
Run Code Online (Sandbox Code Playgroud)

这在第一次调用时效果很好。控制台上新输出的文本颜色已更改,并返回以前的属性。但是,当我第二次调用此函数来重置属性时,GetStdHandle会返回一个与上次调用相同的句柄,但该句柄现在无效(因为我关闭了它)。

当然,当我尝试使用句柄时,这会导致错误。conHandle如果我创建一个静态变量并且仅在等于零GetStdHandle时调用(RealBasic 中新数字变量的默认值),它就可以正常工作。conHandle

我总是被告知要自己清理。我应该让这个手柄保持打开状态吗?

Nor*_*elm 5

是的,您应该让手柄保持打开状态。

当您的进程退出时,该句柄会自动关闭。