Skip to content

Set Region property before Control handle created take no effect #14020

@chenYL123djdj

Description

@chenYL123djdj

.NET version

10.0.100-rc.2.25502.107

Did it work in .NET Framework?

Yes

Did it work in any of the earlier releases of .NET Core or .NET 5+?

.NET 8.0.21

Issue description

Set Region property before Control handle created take no effect.
Use following code:

private void button1_Click(object sender, EventArgs e)
{
    var button = new Button()
    {
        Size = new Size(200, 200),
    };
    var path = new GraphicsPath();
    path.AddEllipse(0, 0, button.Width, button.Height);
    button.Region = new Region(path);
    this.Controls.Add(button);
}

It works fine on NET8:
Image

But Region property not take effect on NET10 Preview :
Image

I read the source code, this is because the codeif (oldRegion == region || !IsHandleCreated), oldRegion == region caused SetRegionInternal to return early in OnHandleCreated.

    private Region? SetRegionInternal(Region? region)
    {
        Region? oldRegion = Properties.AddOrRemoveValue(s_regionProperty, region);

        if (oldRegion == region || !IsHandleCreated)
        {
            // We'll get called when OnHandleCreated runs.
            return oldRegion;
        }

        if (region is null)
        {
            PInvoke.SetWindowRgn(this, default, PInvoke.IsWindowVisible(this));
            return oldRegion;
        }

        // If we're an ActiveX control, clone the region so it can potentially be modified
        using Region? regionCopy = IsActiveX ? ActiveXMergeRegion(region.Clone()) : null;
        using RegionScope regionHandle = (regionCopy ?? region).GetRegionScope(HWND);

        if (PInvoke.SetWindowRgn(this, regionHandle, PInvoke.IsWindowVisible(this)) != 0)
        {
            // Success, the window now owns the region
            regionHandle.RelinquishOwnership();
        }

        return oldRegion;
    }

Steps to reproduce

Here is a project to reproduce.
RegionTest.zip

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions