根據 MouseEventArgs 的座標,判斷使用者點擊區域並建立對應的回應物件:
// 左上角調整大小
if ((e.X <= LEFT + 10 && e.Y <= TOP) || (e.Y <= TOP + 10 && e.X <= LEFT))
{
mouse = new MouseSizeTopLeft(Location.X, Location.Y, Width, Height);
return;
}
// 關閉按鈕
if (e.X > Width - 20 && e.Y > 6 && e.X < Width - 20 + SysButton_Min.Width && e.Y < 6 + SysButton_Min.Height)
{
Close();
return;
}
大多數回應在 MouseMove 中完成,使用螢幕絕對座標:
private void Form_MouseMove(object sender, MouseEventArgs e)
{
this.Parent.Cursor = CheckCursorType(e.X, e.Y); // 更新游標樣式
if (mouse != null)
{
// 使用 Control.MousePosition 取得桌面絕對座標
mouse.Action(Control.MousePosition.X, Control.MousePosition.Y, this);
}
}
private void Form_MouseUp(object sender, MouseEventArgs e)
{
mouse = null; // 釋放回應物件
}
private void Form_DoubleClick(object sender, EventArgs e)
{
if (y > TOP && y < TITLE_WIDTH)
{
if (WindowState == FormWindowState.Normal)
{
WindowState = FormWindowState.Maximized;
SysButton = SysButton_Restore;
}
else if (WindowState == FormWindowState.Maximized)
{
WindowState = FormWindowState.Normal;
SysButton = SysButton_Max;
}
Invalidate(); // 重繪
}
}
// 建議設定 MinimumSize 避免視窗縮至不可見
此系列示範如何以自訂類別封裝各種滑鼠互動行為(MouseSizeRight、MouseDrag 等),實現無邊框視窗的完整拖曳、縮放與系統按鈕功能。