using System.Windows.Forms.VisualStyles;
using System.Drawing.Imaging;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DoubleBuffered = true;
}
private class MyControl
{
private Rectangle _bounds;
private Control _parent;
private bool _hover;
private bool _down;
private string _text;
public string Text
{
get => _text;
set
{
_text = value;
if (_parent != null)
{
_parent.Invalidate();
}
}
}
public Rectangle Bounds
{
get => _bounds;
set
{
_bounds = value;
if (_parent != null)
{
_parent.Invalidate();
}
}
}
public Control Parent
{
get => _parent;
set
{
if (_parent == value)
{
return;
}
if (_parent != null)
{
_parent.Paint -= Paint;
_parent.MouseMove -= MouseMove;
_parent.MouseDown -= MouseDown;
_parent.MouseUp -= MouseUp;
_parent.Invalidate();
}
_parent = value;
if (_parent != null)
{
_parent.Paint += Paint;
_parent.MouseMove += MouseMove;
_parent.MouseDown += MouseDown;
_parent.MouseUp += MouseUp;
_parent.Invalidate();
}
}
}
private void MouseUp(object sender, MouseEventArgs e)
{
if ((_parent != null) && (e.Button == MouseButtons.Left) && (_down))
{
_down = false;
_parent.Invalidate();
}
}
private void MouseDown(object sender, MouseEventArgs e)
{
if ((_parent != null) && (e.Button == MouseButtons.Left) && (_hover) && (_down == false))
{
_down = true;
_parent.Invalidate();
}
}
private void MouseMove(object sender, MouseEventArgs e)
{
if (_parent == null)
{
return;
}
var newHover = (_parent.RectangleToScreen(_bounds).Contains(MousePosition));
if (_hover != newHover)
{
_hover = newHover;
_down = false;
_parent.Invalidate();
}
}
private void Paint(object sender, PaintEventArgs e)
{
if (_parent == null)
{
return;
}
var src = new Rectangle(Point.Empty, _bounds.Size);
using (var bitmap = new Bitmap(_bounds.Width, _bounds.Height, PixelFormat.Format32bppPArgb))
{
using (var g = Graphics.FromImage(bitmap))
{
PushButtonState state;
if (_down)
{
state = PushButtonState.Pressed;
}
else if (_hover)
{
state = PushButtonState.Hot;
}
else
{
state = PushButtonState.Normal;
}
ButtonRenderer.DrawButton(g, src, state);
g.DrawString(_text, _parent.Font, SystemBrushes.ControlText, src
, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
}
for (var y = 0; y < bitmap.Height; y++)
{
for (var x = 0; x < bitmap.Width; x++)
{
var c = bitmap.GetPixel(x, y);
bitmap.SetPixel(x, y, Color.FromArgb((int)(c.A * 0.7), c));
}
}
e.Graphics.DrawImage(bitmap, _bounds, src, GraphicsUnit.Pixel);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
var c1 = new MyControl() { Text = "Control1", Bounds = new Rectangle(10, 10, 100, 35), Parent = this };
var c2 = new MyControl() { Text = "Control2", Bounds = new Rectangle(50, 25, 100, 35), Parent = this };
var c3 = new MyControl() { Text = "Control3", Bounds = new Rectangle(10, 50, 100, 35), Parent = this };
}
}