winapi - 第二次调用 GetStdHandle 返回一个 "invalid"句柄

标签 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

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

当然,当我尝试使用句柄时,这会导致错误。如果我将 conHandle 设置为静态变量并且仅在 conHandle 等于零(新数值变量的默认值)时才调用 GetStdHandle真实基础。)

我总是被告知要清理自己。我应该让这个句柄打开吗?

最佳答案

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

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

关于winapi - 第二次调用 GetStdHandle 返回一个 "invalid"句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8277358/

相关文章:

c++ - 使用 WINRM 在远程主机上推送二进制文件

c++ - 在 Windows 中创建 C++ 非阻塞计时器

c - 如何从 Microsoft RPC Server 调用线程中的回调函数

c - 如果键盘中断作为输入,执行在哪里停止?

c# - 如何实时查看控制台,同时将 stdout 和 stderr 输出到文件

c - 使用 Tab 移动到主应用程序窗口中的另一个编辑控件

windows - 使用 realbasic 获取 Windows 上的 CPU 数量

delphi - 为什么从代码中调用事件处理程序是不好的做法?

linux - REALbasic 相当于 Linux

c# - Console.SetWindowSize() 和 Console.Clear() 未按预期工作