📄 custombutton.cs
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace CustomWinControls
{
public partial class CustomButton : Control
{
private Rectangle clickRectangleValue = new Rectangle();
private PushButtonState state = PushButtonState.Normal;
public CustomButton()
{
this.Width = 100;
this.Height = 40;
InitializeComponent();
}
//定义单击按钮后的小按钮矩形边界
public Rectangle ClickRectangle
{
get
{
clickRectangleValue.X = ClientRectangle.X +
(int)(.2 * ClientRectangle.Width);
clickRectangleValue.Y = ClientRectangle.Y +
(int)(.2 * ClientRectangle.Height);
clickRectangleValue.Width = ClientRectangle.Width -
(int)(.4 * ClientRectangle.Width);
clickRectangleValue.Height = ClientRectangle.Height -
(int)(.4 * ClientRectangle.Height);
return clickRectangleValue;
}
}
// Draw the large or small button, depending on the current state.
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
// 如果按钮被按下去,则绘制小的按钮图形界面
if (state == PushButtonState.Pressed)
{
//Application.RenderWithVisualStyles属性获取当前应用程序
//是否使用可视样式绘制控件;当未启动时,设置为其父级的背景色
this.BackColor = Application.RenderWithVisualStyles ?
Color.Azure : this.Parent.BackColor;
//变为小按钮后,原按钮的一部分将显现出来,
//需要调用DrawParentBackground方法重新绘制
//使其变为父级的背景。
ButtonRenderer.DrawParentBackground(pe.Graphics, ClientRectangle, this);
ButtonRenderer.DrawButton(pe.Graphics, ClickRectangle,
this.Text, this.Font, true, state);
}
//绘制大的未被按下去的按钮图形界面
else
{
ButtonRenderer.DrawButton(pe.Graphics, ClientRectangle, this.Text, this.Font, false, state);
}
}
// Draw the smaller pressed button image.
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
state = PushButtonState.Pressed;
Invalidate();
}
// Draw the button in the hot state.
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
//设置按钮状态为激活状态
state = PushButtonState.Hot;
Invalidate();
}
// Draw the button in the unpressed state.
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
state = PushButtonState.Normal;
Invalidate();
}
// Draw the button hot if the mouse is released on the button.
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
OnMouseEnter(e);
}
// Detect when the cursor leaves the button area while
// it is pressed.
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
// 鼠标左键按下并且光标从按下的按钮上离开时,
// 恢复按钮的正常外观。
if ((e.Button & MouseButtons.Left) == MouseButtons.Left &&
!ClientRectangle.Contains(e.Location) &&
state == PushButtonState.Pressed)
{
OnMouseLeave(e);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -