【问题标题】:Release DC before or after Graphics.Dispose?在 Graphics.Dispose 之前或之后释放 DC?
【发布时间】:2012-06-06 08:49:32
【问题描述】:

在 Windows 窗体的背面,我得到一个窗口 DC,使用 Graphics.FromHdc 创建一个 Graphics 对象,然后在释放 DC 之前处置该 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

Graphics.FromHdc 的 Microsoft 文档显示了类似的代码。 (它使用Graphics.GetHdcGraphics.ReleaseHdc,而不是Win32 GetWindowDcReleaseDC。)但是,它们释放图形对象之前释放DC:

' 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之前还是之后发布? 错误的顺序有没有可能导致资源泄漏或内存损坏?

【问题讨论】:

    标签: .net vb.net winforms gdi+ gdi


    【解决方案1】:

    来自 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 release dc是否也处理本机设备上下文

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 2016-07-11
      • 2011-03-07
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      相关资源
      最近更新 更多