方法一:重寫WndProc()
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 0x84;
const int HTCLIENT = 0x01;
const int HTCAPTION = 0x02;
const int WM_SYSCOMMAND = 0x112;
const int SC_MAXMIZE = 0xF030;
const int WM_NCLBUTTONDBLCLK = 0xA3;
switch (m.Msg)
{
case 0x4e:
case 0xd:
case 0xe:
case 0x14:
base.WndProc(ref m);
break;
case WM_NCHITTEST://鼠标点任意位置后可以拖动窗体
this.DefWndProc(ref m);
if (m.Result.ToInt32() == HTCLIENT)
{
m.Result = new IntPtr(HTCAPTION);
return;
}
break;
case WM_NCLBUTTONDBLCLK://禁止双击最大化
Console.WriteLine(this.WindowState);
return;
break;
default:
base.WndProc(ref m);
break;
}
}
方法二:消息機制
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
[DllImport("user32.dll")]
static extern bool ReleaseCapture();
const int WM_SYSCOMMAND = 0x0112;
const int HTCAPTION = 0x02;
const int SC_MAXMIZE = 0xF030;
const int SC_MOVE = 0xF010;
const int WM_NCLBUTTONDBLCLK = 0xA3;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}