1

Windowsフォームの背面で、ウィンドウDCを取得し、を使用してGraphicsオブジェクトを作成し、DCを解放する前にGraphics.FromHdcGraphicsオブジェクトを破棄します。

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.ReleaseHdcGetWindowDcReleaseDC

' 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ますか?順序を間違えると、リソースリークやメモリ破損が発生する可能性がありますか?

4

1 に答える 1

2

Graphics.Dispose メソッドから:

private void Dispose(bool disposing)
{
..SNIP...
    if (this.nativeGraphics != IntPtr.Zero)
    {
        try
        {
            if (this.nativeHdc != IntPtr.Zero) <<---
            {
                this.ReleaseHdc(); <<--- 
    }

したがって、hdcを単独でリリースするようです。

[編集]

それは実際には:

[DllImport("gdiplus.dll", CharSet = CharSet.Unicode, EntryPoint = "GdipReleaseDC",     ExactSpelling = true, SetLastError = true)]
private static extern int IntGdipReleaseDC(HandleRef graphics, HandleRef hdc);

それが呼び出されています。gdiplus リリース dc がネイティブ デバイス コンテキストも処理するかどうかはわかりません

于 2012-06-01T05:37:08.020 に答える