由于最近在写不规则窗体,看到 侧身象南边 写的这篇文章,恰恰遇到了文中的问题,觉得比较典型,故转载,文章所有权归原作者所有.
在
.NET
中制做不规则形状的窗体有两种方法,一种是重写
onpaint
函数,另一种比较简单的方法是使用不规则的图片做背景,然后设置相关的属性。这里介绍的是后者,以及使用这种方法的一些细节问题:
1.
首先准备一张不规则的背景图片,例如一张圆角边框的图片
2.
新建项目,将窗体
FormBorderStyle
设置为
none
,以去掉标题栏。设置
BackgroundImage
。
3.
设置窗体的
TransparencyKey
属性为图片中圆角边框之外的颜色,窗体在遇到该颜色将显示为透明
通常这种做法是
OK
的,运行即可看到效果
但是有几个值得注意的问题:
1.
所使用的背景图片,圆角边框之外的颜色最好不要使用透明、白色、或黑色。举个例子,使用白色,则
TransparencyKey
将设置为白色,如果你的窗体上有
checkbox
一类的控件,你会发现你点不中小框了,因为小框的白色部分此时变为透明。透明、黑色原因相同。在下面的例子中,我用的是黄色。
2.
如果你的显示器显示设置高于
24
位色,会发现
TransparencyKey
设置不起作用了。这是微软的一个
bug
,有一种解决办法是,先将背景图片添加到资源文件,然后在窗体构造时为窗体设置背景图片:
Bitmap
bmp = AppResource.bg01;
bmp.MakeTransparent(Color.Yellow);
this
.BackColor = Color.Yellow;
this
.BackgroundImage = bmp;
this
.TransparencyKey = Color.Yellow;
3.
背景图片最好使用位图,试了试jpg,好像有问题。
以下是代码,包括添加鼠标事件以便可以拖动窗体:
private
bool isMouseDown = false;
private
Point position;
public
MainForm()
{
InitializeComponent();
Bitmap bmp = AppResource.bg01;
bmp.MakeTransparent(Color.Yellow);
this.BackColor = Color.Yellow;
this.BackgroundImage = bmp;
this.TransparencyKey = Color.Yellow;
}
private
void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private
void MainForm_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int x = -e.X;
int y = -e.Y;
position = new Point(x, y);
isMouseDown = true;
}
}
private
void MainForm_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
Point newPosition = Control.MousePosition;
newPosition.Offset(position);
this.Location = newPosition;
}
}
private
void MainForm_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}