Windowsフォームの背面で、ウィンドウDCを取得し、を使用してGraphicsオブジェクトを作成し、DCを解放する前にGraphics.FromHdc
Graphicsオブジェクトを破棄します。
Private Declare Function GetWindowDC Lib "user32.dll" (ByVal hwnd As IntPtr) As IntPtr
Private Declare Function ReleaseDC Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal hdc As IntPtr) As Integer
Dim hdc As IntPtr = GetWindowDC(Me.Handle)
Try
Using g As Graphics = Graphics.FromHdc(hdc)
' ... use g ...
End Using
Finally
ReleaseDC(Me.Handle, hdc)
End Try
のMicrosoftドキュメントにGraphics.FromHdc
は、同様のコードが示されています。(Win32との代わりにGraphics.GetHdc
とを使用します。)ただし、 Graphicsオブジェクトを破棄する前にDCを解放します。Graphics.ReleaseHdc
GetWindowDc
ReleaseDC
' Get handle to device context.
Dim hdc As IntPtr = e.Graphics.GetHdc()
' Create new graphics object using handle to device context.
Dim newGraphics As Graphics = Graphics.FromHdc(hdc)
' Draw rectangle to screen.
newGraphics.DrawRectangle(New Pen(Color.Red, 3), 0, 0, 200, 100)
' Release handle to device context and dispose of the Graphics ' object
e.Graphics.ReleaseHdc(hdc)
newGraphics.Dispose()
なぜ彼らはそれをこのようにしたのですか?DCはリリースの前または後にリリースする必要がありGraphics.Dispose
ますか?順序を間違えると、リソースリークやメモリ破損が発生する可能性がありますか?