WinForm項目中經常會去掉窗體的邊框,但又需要實現如最小化、關閉這樣的功能。整理一下方便下次解決問題:
隱藏邊框:只需要在窗體屬性上將FormBorderStyle屬性設置為None即可;
隱藏之后實現鼠標拖拽窗體:
#region 鼠標拖拽窗體
const int WM_NCLBUTTONDOWN = 0xA1;
const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
// 窗體上鼠標按下時
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left & this.WindowState == FormWindowState.Normal)
{
// 移動窗體
this.Capture = false;
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
#endregion
任務欄最小化和還原
#region 任務欄最小化/還原操作
protected override CreateParams CreateParams
{
get
{
const int WS_MINIMIZEBOX = 0x00020000; // Winuser.h中定義
CreateParams cp = base.CreateParams;
cp.Style = cp.Style | WS_MINIMIZEBOX; // 允許最小化操作
return cp;
}
}
#endregion
關閉功能:
只需要放置一個設定好樣式的按鈕,實現點擊事件關閉當前界面即可;
當然你可以加上這段代碼,讓你的關閉顯得酷炫一點:
private void btnClosed_Click(object sender, EventArgs e)
{
for (int iNum = 10; iNum >= 0; iNum--)
{
//變更窗體的不透明度
this.Opacity = 0.1 * iNum;
//暫停
System.Threading.Thread.Sleep(30);
}
Close();
}
最小化功能:
實現方式同關閉一樣:
private void btnMini_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
}
隱藏到托盤:
需要放置NotifyIcon工具,然后在你需要實現隱藏的功能按鈕里(如最小化)添加代碼:
private void btnMini_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
ShowInTaskbar = false; //不顯示在系統任務欄
niKE.Visible = true; //托盤圖標可見
}
雙擊托盤內的圖片實現還原:
private void niKE_DoubleClick(object sender, EventArgs e)
{
ShowInTaskbar = true;
niKE.Visible = false;
Show();
WindowState = FormWindowState.Normal;
}
PS:要想隱藏后托盤可見,需要設置ICON圖標,切記切記!!!