c#輕鬆實現磁性窗口

/// <summary>
/// 磁性窗體函數
/// </summary>
/// <param name="form">窗體控件(通常傳this便可)</param>
/// <param name="space">自定義的與屏幕邊緣的距離</param>
/// <param name="isWorkingArea">是否在屏幕工做區進行該操做(true表示不包括任務欄,false則包括整個屏幕的範圍)</param>
public void Form_Welt(Control form, int space, bool isWorkingArea)
{
//獲取窗體的左上角的x,y座標
int x = form.Location.X;
int y = form.Location.Y;函數

int sW = 0;
int sH = 0;測試

if (isWorkingArea)
{
//獲取屏幕的工做區(不包括任務欄)的寬度和高度
sW = Screen.PrimaryScreen.WorkingArea.Width;
sH = Screen.PrimaryScreen.WorkingArea.Height;
}
else
{
//獲取整個屏幕(包括任務欄)的寬度和高度
sW = Screen.PrimaryScreen.Bounds.Width;
sH = Screen.PrimaryScreen.Bounds.Height;
}this

//若是窗體的左邊緣和屏幕左邊緣的距離在用戶定義的範圍內,則執行左貼邊
if ((x <= space && x > 0) || (Math.Abs(x) <= space && x < 0)) //Math.Abs(x)是取絕對值
{
form.Location = new Point(0, y);
}spa

//若是窗體的上邊緣和屏幕上邊緣的距離在用戶定義的範圍內,則執行上貼邊
if ((y <= space && y > 0) || (Math.Abs(y) <= space && y < 0))
{
form.Location = new Point(x, 0);
}orm


//窗體右邊緣跟屏幕右邊緣的距離
int rightW = sW - form.Right;
//窗體下邊緣跟屏幕下邊緣的距離
int bottomW = sH - form.Bottom;事件

//判斷右邊的狀況
if ((rightW <= space && form.Right < sW) || (Math.Abs(rightW) <= space && rightW < 0))
{
form.Location = new Point(sW - form.Width, y);
}
//判斷下邊的狀況
if ((bottomW <= 10 && form.Bottom < sH) || (Math.Abs(bottomW) <= space && bottomW < 0))
{
form.Location = new Point(x, sH - form.Height);
}
}io

 

看到千千靜聽的窗口能夠在接近屏幕邊緣時貼在邊緣上以爲不錯,本身也有這個須要,因此寫了這個方法,測試了感受還蠻不錯的,哈哈~
使用的時候只要在想應用的窗體的Form_Move(object sender,EventAges e)事件裏面調用便可
ps:不過有時窗體可能會比較閃,這個多是代碼還有待改善,或者是在Form_Move事件裏面來調用不大合適,反正功能是實現了,要是哪位有更好的方法,歡迎回復交流一下啊~form

相關文章
相關標籤/搜索