您的位置:首页 > 编程语言 > C#

C#实现无边框窗体拖动的两个方案

2014-06-01 02:35 531 查看
方案一:通过DllImport方式调用Windows API实现

using System.Runtime.InteropServices;
const int WM_SYSCOMMAND = 0x0112;
const int SC_MOVE = 0xF010;
const int HT_CAPTION = 2;
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HT_CAPTION, 0);
}


方案二:通过重写WndProc窗口过程函数实现

const int WM_NCHITTEST = 0x0084;
const int HT_LEFT = 10;
const int HT_RIGHT = 11;
const int HT_TOP = 12;
const int HT_TOPLEFT = 13;
const int HT_TOPRIGHT = 14;
const int HT_BOTTOM = 15;
const int HT_BOTTOMLEFT = 16;
const int HT_BOTTOMRIGHT = 17;
const int HT_CAPTION = 2;

protected override void WndProc(ref Message Msg)
{
if (Msg.Msg == WM_NCHITTEST)
{
//获取鼠标位置
int nPosX = (Msg.LParam.ToInt32() & 65535);
int nPosY = (Msg.LParam.ToInt32() >> 16);
//右下角
if (nPosX >= this.Right - 6 && nPosY >= this.Bottom - 6)
{
Msg.Result = new IntPtr(HT_BOTTOMRIGHT);
return;
}
//左上角
else if (nPosX <= this.Left + 6 && nPosY <= this.Top + 6)
{
Msg.Result = new IntPtr(HT_TOPLEFT);
return;
}
//左下角
else if (nPosX <= this.Left + 6 && nPosY >= this.Bottom - 6)
{
Msg.Result = new IntPtr(HT_BOTTOMLEFT);
return;
}
//右上角
else if (nPosX >= this.Right - 6 && nPosY <= this.Top + 6)
{
Msg.Result = new IntPtr(HT_TOPRIGHT);
return;
}
else if (nPosX >= this.Right - 2)
{
Msg.Result = new IntPtr(HT_RIGHT);
return;
}
else if (nPosY >= this.Bottom - 2)
{
Msg.Result = new IntPtr(HT_BOTTOM);
return;
}
else if (nPosX <= this.Left + 2)
{
Msg.Result = new IntPtr(HT_LEFT);
return;
}
else if (nPosY <= this.Top + 2)
{
Msg.Result = new IntPtr(HT_TOP);
return;
}
else
{
Msg.Result = new IntPtr(HT_CAPTION);
return;
}
}
base.WndProc(ref Msg);
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# api 鼠标 无边框 拖动