如何在C#.Net中移动窗体?

4
感谢您之前对我的问题的回答。 您可以看以下链接。 如何在C#.Net中最小化和最大化? 现在我面临另一个问题。 当我将窗体的borderstyle更改为none时,我无法像真正的窗体那样移动窗体。 它很稳定,无法移动到任何地方。
在Windows窗体的常规borderstyle可以移动到任何地方。 但我想要在borderstyle的none属性中移动。 我该怎么办? 如果您能,请告诉我。 感谢您的时间。 :)
3个回答

10
public class AppFormBase : Form
{   
    public Point downPoint = Point.Empty;

    protected override void OnLoad(EventArgs e)
    {
        if (FormBorderStyle == System.Windows.Forms.FormBorderStyle.None)
        {
            MouseDown += new MouseEventHandler(AppFormBase_MouseDown);
            MouseMove += new MouseEventHandler(AppFormBase_MouseMove);
            MouseUp   += new MouseEventHandler(AppFormBase_MouseUp);
        }

        base.OnLoad(e);
    }

    private void AppFormBase_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            downPoint = new Point(e.X, e.Y);
    }
    private void AppFormBase_MouseMove(object sender, MouseEventArgs e)
    {
        if (downPoint != Point.Empty)
            Location = new Point(Left + e.X - downPoint.X, Top + e.Y, - downPoint.Y);
    }
    private void AppFormBase_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            downPoint = Point.Empty;
    }
}

不错的回答。@Seven - 如果“可移动”窗体包含您想要使用鼠标抓取的控件,则还需要使用Gabriel编写的处理程序来处理这些控件的MouseMove/MouseDown/MouseUp事件。 - Steve Wong

4
请看这个教程:http://www.codeproject.com/KB/cs/csharpmovewindow.aspx
以下是主要内容:
using System.Runtime.InteropServices;

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();

private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{     
    if (e.Button == MouseButtons.Left)
    {
        ReleaseCapture();
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
    }
}

1
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    Capture = false;
    Message msg = Message.Create(Handle, WM_NCLBUTTONDOWN, (IntPtr)HT_CAPTION, IntPtr.Zero);
base.WndProc(ref msg);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接