日期:2014-05-20  浏览次数:20925 次

Winform中,如何让普通button当被点击时有被压下去的效果?
Winform中,如何让普通button当被点击时有被压下去的效果?


------解决方案--------------------
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.ComponentModel;

namespace AquaButtonTester
{
/// <summary>
/// Summary description for AquaButton.
/// </summary>
[Serializable]
public class AquaButton : System.Windows.Forms.Button
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private bool pulseOnFocus;

///
///Additional variables to handle pulsing
///
private ImageAttributes imgAttr = new ImageAttributes();
private float gamma;
private float minGamma;
private float maxGamma;
private float gammaStep;
private Timer pulseTimer = new Timer();
private Bitmap buttonBitmap;
private Rectangle buttonBitmapRectangle;

public AquaButton()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();

mouseAction = MouseActionType.None;

this.SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.DoubleBuffer |
ControlStyles.UserPaint, true);

//The following defaults are better suited to draw the text outline
this.Font = new Font( "Arial Black ", 12, FontStyle.Bold);
this.BackColor = Color.DarkTurquoise;
this.Size = new Size(112, 48);

//Initialize variables to Pulse button
gamma = 1.0f;
minGamma = 1.0f;
maxGamma = 2.2f;
gammaStep = .2f;
pulseTimer.Interval = 90;
pulseTimer.Tick +=new EventHandler(pulseTimer_Tick);
}

[DefaultValue(false)]
public bool PulseOnFocus
{
get { return pulseOnFocus; }
set { pulseOnFocus = value; Invalidate(); }
}


/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion

private enum MouseActionType
{
None,
Hover,
Click
}

private MouseActionType mouseAction;

protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(Color.White);
Color clr = this.BackColor;
int shadowOffset = 8;
int btnOffset = 0;
switch (mouseAction)
{
case MouseActionType.Click:
shadowOffset = 4;
clr = Color.Gold;
btnOffset = 2;
break;
case MouseActionType.Hover:
clr = Color.Gold;
break;
}
g.SmoothingMode = SmoothingMode.AntiAlias;

///
/// Create main colored shape
///
Rectangle rc = new Rectangle(btnOffset,btnOffset,this.ClientSize.Width-8-btnOffset, this.ClientSize.Height-8-btnOffset);