Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move form in C#.Net? [duplicate]

Tags:

c#

.net

winforms

Thanks you for your previous answers for my question. you can see following link.

How to minimize and maximize in C#.Net?

Now i'm facing another problem. When i changed my form's borderstyle to none,i can't move form like the real form. Its stable and can't move anywhere.

In Windows form's normal borderstyle can move anywhere. But i want to move like that in borderstyle's none property. How can i do that? Please let me know if you can. Thanks you for your time. :)

like image 655
Seven Avatar asked Dec 06 '22 19:12

Seven


2 Answers

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;
    }
}
like image 138
Aaron Anodide Avatar answered Dec 20 '22 20:12

Aaron Anodide


Take a look at this tutorial: http://www.codeproject.com/KB/cs/csharpmovewindow.aspx.

Here's the gist of it:

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);
    }
}
like image 24
James Hill Avatar answered Dec 20 '22 21:12

James Hill