blavince's BLOG

Giving is a reward in itself.

0%

Winform UI 客製化(一) - 窗體

使用者界面, 又稱 用戶介面 或 人機互動界面 (User Interface 或 User Machine Interface,簡稱 UI).
因為 Winform 自帶的 UI 實在硬梆梆, 所以在可變更的範圍內設計自己喜歡的 UI.

前言

參考 Visual studio + C# 建立 Winform 專案 建立 Winform 專案.

本文

  1. 窗體客制化
  2. 善用 Panel 控件排版
  3. 控件客制化
  4. 互動代碼

1. 窗體客製化

  • 取消窗框:

將 Form1 的窗體屬性 (FormBoarderStyle) 從默認的 Sizable 改成 None:

可以看到窗體的邊框不見了,

運行後, 會發現應用程式無法移動也無法關閉, 這部分在文章後面會編寫相關代碼.

2. 善用 Panel 控件排版

  • Panel 控件 + Dock 屬性:
    控件的 Dock 屬性可以選擇靠齊 (上、下、左、右、填滿或者無). 使用 panel 控件搭配 Dock 屬性可以輕易地整齊排版.
    從工具箱拉 panel 控件做以下修改作為標題欄:
    • BackColor: 41, 44, 50
    • Dock: Top

3. 控件客製化

可以在控件屬性直接修改, 也可以在代碼內再做修改.

  1. 修改 Form1 :
    • BackColor: 41, 53, 65
  2. 新增 button1 :
    • BackColor: 41, 53, 65
    • FlatStyle: Flat
    • ForeColor: LightGray
  3. 新增 label1:
    • BackColor: 41, 53, 65
    • ForeColor: LightGray
  4. 新增 label2:
    • BackColor: 41, 53, 65
    • ForeColor: LightGray
    • Text: X
  5. 新增 label3:
    • BackColor: 41, 53, 65
    • ForeColor: LightGray
    • Text: blavince’s BLOG

4. 互動代碼

  • 標題欄拖曳窗體:
    編寫代碼賦予標題欄拖曳時可以移動窗體, 透過 panel1 的三個滑鼠事件達成這個功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
private bool beginMove = false;
private int currentXPosition;
private int currentYPosition;

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
beginMove = true;
currentXPosition = MousePosition.X; //滑鼠的 X 座標為當前窗體左上角 X 座標參考
currentYPosition = MousePosition.Y; //滑鼠的 Y 座標為當前窗體左上角 Y 座標參考
}
}

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (beginMove)
{
this.Left += MousePosition.X - currentXPosition; //根據滑鼠的 X 座標確定窗體的 X 座標
this.Top += MousePosition.Y - currentYPosition; //根據滑鼠的 Y 座標確定窗體的 Y 座標
currentXPosition = MousePosition.X;
currentYPosition = MousePosition.Y;
}
}

private void panel1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
currentXPosition = 0; //設定初始狀態
currentYPosition = 0; //設定初始狀態
beginMove = false;
}
}

同理, 編寫其他控件的三個滑鼠事件也能拖曳移動窗體.

  • 關閉應用程式:
    雙擊 label2 帶出 Click function 並加入以下代碼:
    1
    2
    3
    4
    private void label2_Click(object sender, EventArgs e)
    {
    Application.Exit();
    }
    令窗體右上角「X」點擊時呼叫 Application.Exit() 關閉應用程式!
  • 編譯運行
    點擊 偵錯(D)開始偵錯(G), 編譯完成後運行如下圖:

    點擊 button1 按鈕後, label1 顯示 Hello World!