C# 開發圓角窗體

   因爲項目需要做個Winform的隨機啓動的數據上傳工具,用Visual Studio的窗體感覺太醜了,就想進行優化,反正就一個窗體,上面也沒啥按鈕,就不要標題欄了,就搞一個圓角的窗體好了,搞個漂亮的背景圖片。上面搞一個最小化和關閉按鈕。把窗體設置爲圓角窗口的操作如下:

    1、把窗體frmMain的FormBorderStyle屬性設置爲None,去掉窗體的邊框,讓窗體成爲無邊框的窗體。

    2、設置窗體的Region屬性,該屬性設置窗體的有效區域,我們把窗體的有效區域設置爲圓角矩形,窗體就變成圓角的。

    3、添加兩個控件,控制窗體的最小化和關閉。

    設置爲圓角窗體,主要涉及GDI+中兩個重要的類 Graphics和GraphicsPath類,分別位於System.Drawing和System.Drawing.Drawing2D。

  接着我們需要這樣一個函數 private void SetWindowRegion() 此函數設置窗體有效區域爲圓角矩形,以及一個輔助函數 private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)此函數用來創建圓角矩形路徑,將在SetWindowRegion()中調用它。

ublic void SetWindowRegion()  
{  
    System.Drawing.Drawing2D.GraphicsPath FormPath;  
    FormPath = new System.Drawing.Drawing2D.GraphicsPath();  
    Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);  
    FormPath = GetRoundedRectPath(rect, 10);  
    this.Region = new Region(FormPath);    
}  
private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)  
{  
    int diameter = radius;  
    Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));  
    GraphicsPath path = new GraphicsPath();    
    // 左上角  
    path.AddArc(arcRect, 180, 90);    
    // 右上角  
    arcRect.X = rect.Right - diameter;  
    path.AddArc(arcRect, 270, 90);    
    // 右下角  
    arcRect.Y = rect.Bottom - diameter;  
    path.AddArc(arcRect, 0, 90);    
    // 左下角  
    arcRect.X = rect.Left;  
    path.AddArc(arcRect, 90, 90);  
    path.CloseFigure();//閉合曲線  
    return path;  
}

   在窗體尺寸改變的時候我們需要調用SetWindowRegion()將窗體變成圓角的。

private void frmMain_Resize(object sender, EventArgs e)
{
    SetWindowRegion();
}

設置按鈕的形狀:

   添加兩個普通的按鈕button,設置按鈕的BackColor屬性爲Transparent,讓背景透明,不然按鈕的背景色與窗體的圖片背景不相符。設置按鈕的FlatStyle屬性爲Flat,同時設置FlatAppearance屬性中的BorderSize=0,MouseDownBackColor和MouseOverBackColor的值均爲Transparent,防止點擊按鈕時,顏色變化影響美觀。調整按鈕的大小和位置即可。最小化和關閉按鈕(是右下角托盤,所以沒有退出程序)的代碼如下:

private void btn_min_Click(object sender, EventArgs e)
{
	this.WindowState = FormWindowState.Minimized;
}
private void btn_close_Click(object sender, EventArgs e)
{
	this.WindowState = FormWindowState.Minimized;
	this.Hide();
}

  還可以添加代碼,控制鼠標移動到操作按鈕上時,改變按鈕上文字的顏色,來增加體驗。

程序界面如下圖

wKiom1jMn5ziiYzEAAA07H8OaNo971.jpg-wh_50

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章