有时进行界面创作,为了达到个性鲜明标新立异的效果,往往会想到建立不同形状不同外观的窗体。
下面就介绍两种建立不规则窗体的方法。
首先在命名空间引用using System.Drawing.Drawing2D。
以下建立椭圆形窗体:
添加窗体Paint事件
private void Form1_Paint(object sender, PaintEventArgs e)
{
GraphicsPath creatnewform = new GraphicsPath();
creatnewform.AddEllipse(10, 50, this.Width - 80, this.Height - 100); //创建椭圆形区域
this.Region = new Region(creatnewform);
}
运行后即生成一个无边缘的纯椭圆形的窗体。为方便窗体的关闭,可以设置一个button作为关闭按钮。
同时,为了增加窗体的外观颜色等,可以设置相应的窗体背景,使其美观。
建立多边形窗体:
同样添加Paint事件
private void Form1_Paint(object sender, PaintEventArgs e)
{ //建立5边形窗体
GraphicsPath creatnewform = new GraphicsPath();
Point[] myform={new Point(230,200),
new Point(400,100),
new Point(570,200),
new Point(500,400),
new Point(300,400),}
creatnewform.AddPloygon(Myform); //多边形函数
this.Region=new Region(creatnewform);
}
为了使窗体可以受鼠标控制移动,则需要添加如下事件代码:
private Point MousePos; //纪录鼠标指针的坐标
private bool bMouseDown = false; //纪录鼠标左键是否按下
private void Form1_MouseDown(object sender, MouseEventArgs e)//鼠标键按下
{
if (e.Button == MouseButtons.Left)
{
MousePos.X = -e.X - SystemInformation.FrameBorderSize.Width;
MousePos.Y = -e.Y - SystemInformation.CaptionHeight - SystemInformation.FrameBorderSize.Height;
bMouseDown = true;
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e) //鼠标移动
{
if (bMouseDown)
{
Point CurrentPos = Control.MousePosition;
CurrentPos.Offset(MousePos.X, MousePos.Y);
Location = CurrentPos; //当前位置
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e) //鼠标弹起
{
if (e.Button == MouseButtons.Left)
{
bMouseDown = false;
}
}