Question

I'm working on making a program that has no control box, because I don't want one. I am trying to make it so that when I click any area that is not a control, it will move. This is the code I have so far:

    public Form1()
    {
        InitializeComponent();
        BackColor = Color.linen;
        TransparencyKey = Color.Linen;
    }
    bool canMove = false;
    int mouseX;
    int mouseY;
    public void MoveForm()
    {
        mouseX = MousePosition.X - Form1.ActiveForm.Location.X;
        mouseY = MousePosition.Y - Form1.ActiveForm.Location.Y;
        Form1.ActiveForm.Location = new Point(mouseX, mouseY);
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        canMove = true;
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (canMove)
            MoveForm();

    }

    private void Form1_MouseUp(object sender, MouseEventArgs e)
    {
        canMove = false;
    }

That works for moving, but if the form is at an edge, it will not show up right. Another thing it does, is flashes when it is getting dragged.

Is there any way I can correctly do this?

Was it helpful?

Solution

Just add this code to form and you're done:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private const int HTCLIENT = 0x0001;
    private const int HTCAPTION = 0x0002;
    private const int WM_NCHITTEST = 0x0084;

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if ((m.Msg == WM_NCHITTEST) & (m.Result.ToInt32() == HTCLIENT))
        {
            m.Result = (IntPtr)HTCAPTION;
        }
    }

}

OTHER TIPS

The code is in vb (sorry):

Private posx, posy As Integer

Private Sub Form1_MouseDown(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
    canMove = 1

    posx = MousePosition.X
    posy = MousePosition.Y
End Sub

Private Sub Form1_MouseMove(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
    If canMove = 1 And (posx <> MousePosition.X Or posy <> MousePosition.Y) Then
        MoveForm()
    End If

    posx = MousePosition.X
    posy = MousePosition.Y
End Sub

It does go back and forth(its because of your code in MoveForm()) but if you don't move the mouse it stops.

Edit: in c# (used translator)

int posx, posy;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    canMove = true;
    posx = MousePosition.X;
    posy = MousePosition.Y;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (canMove == 1 && (posx != MousePosition.X || posy != MousePosition.Y)) {
        MoveForm();
    }

    posx = MousePosition.X;
    posy = MousePosition.Y;
}

valter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top