如何在c# . net中移动表单

本文关键字:移动 表单 net | 更新日期: 2023-09-27 18:07:28

感谢您之前对我问题的回答。你可以看到下面的链接。

如何在c# .Net中最小化和最大化?

现在我面临另一个问题。当我改变我的形式的borderstyle为none,我不能像真正的形式移动形式。它很稳定,不能移动。

在Windows窗体的正常边界样式可以移动到任何地方。但我想在borderstyle的none属性中这样移动。我怎么能做到呢?如果可以,请告诉我。谢谢你的宝贵时间。:)

如何在c# . net中移动表单

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;
    }
}

看看这个教程: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);
    }
}
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);
}