using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Ellipse_Control
{
internal class EllipseTool : Component
{
[DllImport("Gdi32.dll", SetLastError = true)]
private static extern IntPtr CreateRoundRectRgn(
int nLeftRect,
int nTopRect,
int nRightRect,
int nBottomRect,
int nWidthEllipse,
int nHeightEllipse);
private Control _targetControl;
private int _cornerRadius = 30;
private readonly EventHandler _sizeChangedHandler;
public EllipseTool()
{
_sizeChangedHandler = new EventHandler(OnControlSizeChanged);
}
[Category("Appearance")]
public Control TargetControl
{
get => _targetControl;
set
{
if (_targetControl != null)
{
_targetControl.SizeChanged -= _sizeChangedHandler;
}
_targetControl = value;
if (_targetControl != null)
{
_targetControl.SizeChanged += _sizeChangedHandler;
UpdateRegion();
}
}
}
[Category("Appearance")]
public int CornerRadius
{
get => _cornerRadius;
set
{
_cornerRadius = value;
UpdateRegion();
}
}
private void OnControlSizeChanged(object sender, EventArgs e)
{
UpdateRegion();
}
private void UpdateRegion()
{
if (_targetControl == null || _targetControl.IsDisposed) return;
IntPtr regionHandle = CreateRoundRectRgn(
0, 0,
_targetControl.Width + 1,
_targetControl.Height + 1,
_cornerRadius,
_cornerRadius);
_targetControl.Region = Region.FromHrgn(regionHandle);
}
}
}