无边框Winform窗体移动的几种方式

来源:互联网 发布:linux usr目录 编辑:程序博客网 时间:2024/05/21 12:25

    当把Winform的FormBorderStyle设置为None的时候,因为窗体没有了标题栏,所以不能够移动窗体,

而是用如下几种方法,便可以在此情况下,通过点击窗体来移动窗体:

 

一、是用重载WndProc消息的方法:

       大概原理是利用原来Windows对鼠标在标题栏上活动(鼠标按下、移动、鼠标抬起)的响应(移动),

即获取到鼠标在客户区活动的消息后,改变消息返回,由客户区改为标题栏区。

 

定义常量:

        const int WM_NCHITTEST = 0x0084;   \\Windows用来获取鼠标命中在窗体的哪个部分

        const int HTCAPTION = 2;   //标题栏
        const int HTCLIENT = 1;      //客户区

重载方法:

 

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            switch (m.Msg)
            {
                case WM_NCHITTEST:
                    if (m.Result == (IntPtr)HTCLIENT)
                        m.Result = (IntPtr)HTCAPTION;
                    break;
            }
        }

 

相关参考:http://www.cnblogs.com/GnagWang/archive/2010/09/12/1824394.html

 

 

二、当MouseDown时,发送移动消息的方法:

定义常量:

 

public const uint WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 61456;
public const int HTCAPTION = 2;   \\标题栏

 

声明Windows API:

 

[DllImport("User32.DLL")]
public static extern bool ReleaseCapture();
 
[DllImport("User32.DLL")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

 

定义MouseDown事件:

 

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    ReleaseCapture();
    SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
}

 

 

三、在MouseDown时记录鼠标位置并修改移动标记为true,在MouseMove并且移动标记为true时,根据新鼠标位置和原来鼠标位置进行移动,并

       重新记录新的鼠标位置,在MouseUp时,修改移动标记为false。

 

声明变量:

Point mouse;

bool Capture;

 

定义事件:

MouseDown(object sender,MouseEventArgs e)

{

    mouse=e.Location;

    Capture=true;

}

 

MouseMove(object sender,MouseEventArgs e)

{

    if(this.Capture)

    {

        Point p=Control.MousePosition;

        p.Offset(-mouse.X,-mouse.Y)

        ctrl.Location=p;  (ctrl为要移动的窗体或者控件)

    }

}

 

MouseUp(object sender,MouseEventArgs e)

{

    this.Capture=false;

}

 

 

 

      

原创粉丝点击