make a window in c# code example
Example: how to custom window in C#
public class Win32
{
[DllImport("user32")]
public static extern bool ReleaseCapture();
[DllImport("user32")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wp, int lp);
}
public class CustomWindow : ContainerControl
{
private Color headerBack = Color.FromArgb(44, 52, 63);
private Color containerBack = Color.FromArgb(36, 41, 49);
private Color borderBack = Color.Silver;
private string title = "CustomWindow";
private bool supportsIcon = true;
private Font titleFont = new Font("Segoe UI", 12F);
private Color titleColr = Color.FromArgb(243, 243, 243);
private Rectangle headerRect, containerRect, borderRect, titleRect;
private Image icon;
public Color HeaderBackground
{
get => headerBack;
set { headerBack = value; Invalidate(); }
}
public Color ContainerBackground
{
get => containerBack;
set { containerBack = value; Invalidate(); }
}
public Color Border
{
get => borderBack;
set { borderBack = value; Invalidate(); }
}
public string Title
{
get => title;
set { title = value; Invalidate(); }
}
public Font TitleFont
{
get => titleFont;
set { titleFont = value; Invalidate(); }
}
public Color TitleColor
{
get => titleColor;
set { titleColor = value; Invalidate(); }
}
public bool SupportsIcon
{
get => supportsIcon;
set { supportsIcon = value; Invalidate(); }
}
public Image Icon
{
get => icon;
set { icon = value; Invalidate(); }
}
public CustomWindow()
{
SetStyle(ControlStyles.AllPaintingInWMPaint |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.SupportsTransparentBackColor, true);
DoubleBuffered = true;
if (Parent != null)
Parent.Size = new Size(500, 400);
if (Parent is Form form)
form.FormBorderStyle = FormBorderStyle.None;
Dock = DockStyle.Fill;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
Size titleSize = TextRenderer.MeasureText(title, titleFont);
headerRect = new Rectangle(0, 0, Width, 40);
containerRect = new Rectangle(0, 41, Width, Height - 41);
borderRect = new Rectangle(0, 40, Width, 1);
titleRect = new Rectangle(supportsIcon ? 35 : 10, 10, titleSize.Width, titleSize.Height);
g.FillRectangle(new SolidBrush(headerBack), headerRect);
g.FillRectangle(new SolidBrush(borderBack), borderRect);
g.FillRectangle(new SolidBrush(containerBack), containerRect);
g.DrawString(title, titleFont, new SolidBrush(titleColor), titleRect, new StringFormat
{
Alignment = StringAlignment.Near,
LineAlignment = StringAlignment.Center
});
if (supportsIcon == true)
g.DrawIamge(icon ?? Resources.white_black_round_box, 5, 5, 30, 30);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
Point mpos = new Point(e.X, e.Y);
if (e.Button == MouseButtons.Left)
{
if (headerRect.Contains(mpos))
{
Win32.ReleaseCapture();
Win32.SendMessage(Parent.Handle, 161, 2, 0);
}
}
}
}