答案 0 :(得分:11)
您可以创建一个继承自Button的类,以便将所有样式保存在一个位置。要执行悬停和按下状态,您可以覆盖按钮的鼠标进入/离开事件并更改样式。
以下是我们其中一个项目的示例(我更改了颜色,但您明白了)。我们改变一些颜色你可以切换图像。
public class MossieButton : Button
{
private static Font _normalFont = new Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
private static Color _back = System.Drawing.Color.Grey;
private static Color _border = System.Drawing.Color.Black;
private static Color _activeBorder = System.Drawing.Color.Red;
private static Color _fore = System.Drawing.Color.White;
private static Padding _margin = new System.Windows.Forms.Padding(5, 0, 5, 0);
private static Padding _padding = new System.Windows.Forms.Padding(3, 3, 3, 3);
private static Size _minSize = new System.Drawing.Size(100, 30);
private bool _active;
public MossieButton()
: base()
{
base.Font = _normalFont;
base.BackColor = _border;
base.ForeColor = _fore;
base.FlatAppearance.BorderColor = _back;
base.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
base.Margin = _margin;
base.Padding = _padding;
base.MinimumSize = _minSize;
}
protected override void OnControlAdded(ControlEventArgs e)
{
base.OnControlAdded(e);
UseVisualStyleBackColor = false;
}
protected override void OnMouseEnter(System.EventArgs e)
{
base.OnMouseEnter(e);
if (!_active)
base.FlatAppearance.BorderColor = _activeBorder;
}
protected override void OnMouseLeave(System.EventArgs e)
{
base.OnMouseLeave(e);
if (!_active)
base.FlatAppearance.BorderColor = _border;
}
public void SetStateActive()
{
_active = true;
base.FlatAppearance.BorderColor = _activeBorder;
}
public void SetStateNormal()
{
_active = false;
base.FlatAppearance.BorderColor = _border;
}
}
答案 1 :(得分:2)
无法看到图片,但我猜您可以更改按钮的边框并设置背景图片。
button1.FlatStyle = FlatStyle.Flat;
button1.BackgroundImage = Bitmap.FromFile("image.jpg");
答案 2 :(得分:2)
我认为最简单的方法是设置按钮的一些属性,如下所示
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Image = "Any Image"
this.button1.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button1.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
然后编写
的代码 private void button1_Click(object sender, EventArgs e)
{
//Code for Image Appearance.
button1.Text = "OnClick";
}
private void button1_MouseEnter(object sender, EventArgs e)
{
//Code for Image Appearance.
button1.Text = "Enter";
}
private void button1_MouseLeave(object sender, EventArgs e)
{
//Code for Image Appearance.
button1.Text = "Normal";
}
更新
我不知道我是否正确但我认为你也可以通过在面板中放置一个按钮和一个标签来根据你的选择安排你的目标。首先使用button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat
设置Label.Text="Normal"
。然后在鼠标上输入面板,绘制一个带有按钮边框的矩形,并将标签文本更改为“Hover
”。就像那样单击面板也可以根据你改变矩形边框并制作label.Text="OnClick"
。