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

方案一:通过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);
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值