我試圖將控制檯的文本顏色設置爲給定顏色,打印一行(或更多),然後將顏色方案改回原來的樣子。這裏是我有什麼:對GetStdHandle的第二次調用返回一個「無效」的句柄
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的新數值變量的默認值。)
,我總是告訴自己以後清理。我應該打開這個手柄嗎?
是的,你應該清理自己,但你也應該被告知要尊重別人的財產。在這種情況下,你沒有創建控制檯句柄,所以你也不應該銷燬它。 –
我以爲我確實創造了手柄,或者至少它是屬於我的。 –
GetStdHandle不創建句柄,它只是獲取現有的句柄。處理創建函數是CreateFile,CreateMutex等。 –