vs.net以及vc++6.0提供的按钮控件都是规则的矩形按钮,但是那些界面非常美观的软件是什么语言开发的呢?其实那些各种形状的按钮都可以使用c++以及c#进行开发,不过今天我要使用的方法是c#下的panel控件进行代替按钮的功能,幸好panel控件有MouseDown、MouseHover、MouseUp、MouseLeave等事件响应。下面讲一下使用方法:
1. 添加命名空间引用:
using System.Drawing.Drawing2D;
2. 双击panel控件,进入下面函数,添加类似代码:
private void panel1_Paint(object sender, PaintEventArgs e) { this.panel1.Cursor = Cursors.Hand; Bitmap bmpBob = (Bitmap)this.panel1.BackgroundImage; GraphicsPath graphicsPath = CalculateControlGraphicsPath(bmpBob); this.panel1.Region = new Region(graphicsPath); }
3. 实现CalculateControlGraphicsPath()函数进行画图片,透明部分不画:
private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap) { GraphicsPath graphicsPath = new GraphicsPath(); Color colorTransparent = bitmap.GetPixel(0, 0); int colOpaquePixel = 0; for (int row = 0; row < bitmap.Height; row++) { colOpaquePixel = 0; for (int col = 0; col < bitmap.Width; col++) { if (bitmap.GetPixel(col, row) != colorTransparent) { colOpaquePixel = col; int colNext = col; for (colNext = colOpaquePixel; colNext < bitmap.Width; colNext++) if (bitmap.GetPixel(colNext, row) == colorTransparent) break; graphicsPath.AddRectangle(new Rectangle(colOpaquePixel, row, colNext - colOpaquePixel, 1)); col = colNext; } } } return graphicsPath; }
4. 实现响应函数:
private void panel1_MouseDown(object sender, MouseEventArgs e) { }
private void panel1_MouseHover(object sender, EventArgs e) { } private void panel1_MouseUp(object sender, MouseEventArgs e) { } private void panel1_MouseLeave(object sender, EventArgs e) { } private void panel1_Click(object sender, EventArgs e) { }
通过测试,只要panel响应事件处理的好,panel的效果要好于button!