WinForm去掉边框实现最小化、关闭、鼠标移动窗体以及隐藏到托盘

    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图标,切记切记!!!

原文地址:https://www.cnblogs.com/GGLoner/p/6704765.html