讓控制元件(Control Components,如按鈕、標籤...等)可以供使用者自由調整大小,首先準備一個小圖示提示使用者該元件可以隨心所欲的調整大小。
接著在Form中新增一個按鈕(Button)元件,並命名為button1,將準備好的提示圖片加入button1的Image屬性,並設定ImageAlign為BottomRight,讓提示圖片顯示在按鈕的右下角。
在Form類別中加入成員屬性
1
| private bool resize = false;
|
最後註冊按鈕的MouseMove事件即可:
在MouseMove事件中加入下列程式碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| private void button1_MouseMove(object sender, MouseEventArgs e)
{
Button btn = (Button)sender;
if (e.Button == MouseButtons.Left && resize)
{
btn.Width = e.X;
btn.Height = e.Y;
}
else
{
Point pt = btn.PointToClient(Control.MousePosition);
if (pt.X > btn.Width - 5 && pt.Y > btn.Height - 5)
{
btn.Cursor = Cursors.SizeNWSE;
resize = true;
}
else
{
btn.Cursor = Cursors.Default;
resize = false;
}
}
}
|
首先判斷滑鼠移入控制元件範圍時resize變數是否已經被設定並且滑鼠左鍵有被按壓,先看else(resize變數還未設定這邊),用Control.MousePosition取得游標在螢幕的座標位置並運用button1的成員函數PointToClient算出游標在button1中的座標,判斷若游標靠近右下角5個畫素點的話就把游標圖示改成調整大小的游標圖示並將resize變數設定為true開啟調整大小的功能,否則將游標還原成預設圖示。
接著看if區塊,只要符合調整大小的要素,就把按鈕的寬高分別指定為e.X與e.Y即可。