C# 无边框 WinForm
如何拖动
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;
private void _headPanel_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;
private void _headPanel_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
如何最大化、还原
Form form = this.FindForm(); // 这里把控制按钮做成了用户控件,如果没有做成用户控件,就不用 FindForm 了。
if (form.WindowState == FormWindowState.Maximized)
{
form.WindowState = FormWindowState.Normal;
}
else if (form.WindowState == FormWindowState.Normal)
{
form.WindowState = FormWindowState.Maximized;
}
if (form.WindowState == FormWindowState.Maximized)
{
form.WindowState = FormWindowState.Normal;
}
else if (form.WindowState == FormWindowState.Normal)
{
form.WindowState = FormWindowState.Maximized;
}
注意 FindForm 不能用在构造函数中,不过可以放在 Load 中。
不能自动最大化的问题
也就是说设置了 WindowState 为 Maximized,但是启动时仍然不是最大化的。
private void Form1_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
}
{
this.WindowState = FormWindowState.Maximized;
}
解决最大化遮住任务栏的问题
private void Main_Load(object sender, EventArgs e)
{
MaximumSize = Screen.PrimaryScreen.WorkingArea.Size;
}
{
MaximumSize = Screen.PrimaryScreen.WorkingArea.Size;
}