實現窗體拖動的兩種方法

方法1:系統消息

protected override void WndProc(ref Message msg)
{
	base.WndProc(ref msg);

	const int WM_NCHITTEST = 0x84;
	const int HTCLIENT = 0x01;

	if (msg.Msg == WM_NCHITTEST)
		if (HTCLIENT == msg.Result.ToInt32())
		{
			Point p = new Point();
			p.X = (msg.LParam.ToInt32() & 0xFFFF);
			p.Y = (msg.LParam.ToInt32() >> 16);

			p = PointToClient(p);

			msg.Result = new IntPtr(2);
		}
}


方法2:事件

private int mx = 0, my = 0;
private bool mc = false;

protected override void OnMouseDown(MouseEventArgs e)
{
	mx = e.X;
	my = e.Y;
	mc = true;
}
protected override void OnMouseMove(MouseEventArgs e)
{
	if (mc == true)
	{
		this.Left = this.Left + (e.X - mx);
		this.Top = this.Top + (e.Y - my);
	}
}
protected override void OnMouseUp(MouseEventArgs e)
{
	mc = false;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章