Home > Enterprise >  How to free HRGN after CreatePolygonRgn?
How to free HRGN after CreatePolygonRgn?

Time:09-17

I wrote a very simple method below in full, it creates a polygon around all components on the TForm. As there is no HRGN.Free method, which the compiler of Delphi XE6 pointed out, I am merely asking if I should Free, well, anything in there, I never used HRGN type before and want to know for sure. Thank you.

PS: I am asking solely on behalf of freeing the memory properly, if even needed here, nothing else.


procedure TFormZoom.SetVisibleFormRegion;

var
    VisibleRegionPoints: array[0..11] of TPoint;
    VisibleFormRegion: HRGN;

begin
    try
        // XY points around all components that we want to be visible on the FormZoom
        VisibleRegionPoints[0] := Point(0, 0);
        VisibleRegionPoints[1] := Point(ZoomBoxPanel.Left   ZoomBoxPanel.Width, 0);
        VisibleRegionPoints[2] := Point(ZoomBoxPanel.Left   ZoomBoxPanel.Width, ZoomBoxPanel.Height);
        VisibleRegionPoints[3] := Point(ZoomBoxPanel.Left, ZoomBoxPanel.Height);
        VisibleRegionPoints[4] := Point(ZoomBoxPanel.Left, 0);
        VisibleRegionPoints[5] := Point(ColorBoxPanel.Width, 0);
        VisibleRegionPoints[6] := Point(ColorBoxPanel.Width, InfoValuesPanel.Top   InfoValuesPanel.Height);
        VisibleRegionPoints[7] := Point(0, InfoValuesPanel.Top   InfoValuesPanel.Height);
        VisibleRegionPoints[8] := Point(0, InfoValuesPanel.Top);
        VisibleRegionPoints[9] := Point(InfoValuesPanel.Width, InfoValuesPanel.Top);
        VisibleRegionPoints[10] := Point(ColorBoxPanel.Width, ColorBoxPanel.Height);
        VisibleRegionPoints[11] := Point(0, ColorBoxPanel.Height);
        try
            // we create a polygon region from the above points
            VisibleFormRegion := CreatePolygonRgn(VisibleRegionPoints, Length(VisibleRegionPoints), ALTERNATE);
            // finally, we set the FormZoom window region to the created polygon
            SetWindowRgn(Self.Handle, VisibleFormRegion, True);
        finally
            VisibleFormRegion.Free;  // <-- There is no method called Free!
        end;
    except
        on E: Exception do
        begin
            // in case of error, we log the exception only
            FormMain.ErrorLog.Add('TFormZoom.SetVisibleFormRegion: '   E.ClassName   ' - '   E.Message);
        end;
    end;
end;

CodePudding user response:

As mentioned in the documentation for CreatePolygonRgn(), the returned handle must be freed with DeleteObject():

When you no longer need the HRGN object, call the DeleteObject function to delete it.

UPDATE

As Remy pointed out: in your case, you're calling SetWindowRgn(), which transfers the ownership of the region to the system. It means that you don't need to free it.

  • Related