winform拖动工作区移动窗体

winform程序中,可以点击标题栏来拖动窗体,如果我们将窗体的边框样式设为None,类似于MSN右下角弹出的消息框,没有标题栏,该如何用鼠标来移动窗体呢?

下面将使用三个方法分别实现无边框窗体的移动

方案1:通过重载消息处理实现。重写窗口过程(WndProc),处理一些非客户区消息(WM_NCxxxx),C#中重写窗口过程不用再调用SetWindowLong API了,直接overide一个WndProc就可以了,不用声明api函数。

鼠标的拖动只对窗体本身有效,不能在窗体上的控件区域点击拖动

 protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == 0x84)
            {
                switch (m.Result.ToInt32())
                {
                    case 1:
                        m.Result = new IntPtr(2);
                        break;
                }
            }
        }



方案2:调用非托管的动态链接库,通过控件的鼠标按下事件(MouseDown)发送一个拖动的消息,可以给控件添加MouseDown事件后,拖动这个控件来移动窗体
using System.Runtime.InteropServices;
[DllImport("User32.DLL")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("User32.DLL")]
public static extern bool ReleaseCapture();
public const uint WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 61456;
public const int HTCAPTION = 2;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    ReleaseCapture();
    SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
}



方案3:能达到的效果和方案2一样,不需要使用外部的动态链接库,直接编写逻辑代码实现,这种方法最简单,最容易理解。可用于任意有鼠标事件的控件和上,可以拖动没有句柄的控件。
Point downPoint;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    downPoint = new Point(e.X, e.Y); 
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        this.Location = new Point(this.Location.X + e.X - downPoint.X, 
            this.Location.Y + e.Y - downPoint.Y);
    } 
}


posted on 2010-05-26 14:33 发布:水寒冰 阅读(313) 评论(0) 收藏 所属分类: ASP.NET(C#)
  • 评论
  • 点击刷新
  • [使用Ctrl+Enter键可以直接提交]

表情图标

[smile][confused][cool][cry][eek][angry][wink][sweat][lol][stun][razz][redface][rolleyes][sad][yes][no][heart][star][music][idea]
Advertise
Category
Time Counter

离十一还有

Recent Article
Statistics
Recent Comments
Archive
Links
Support
《良机》 鲜果阅读器订阅图标
 
TOP