Question Trying to drag the window

glasswizzard

Well-known member
Joined
Nov 22, 2019
Messages
126
Programming Experience
Beginner
Hi, I managed to get this working in winforms a while back but I'm failing to do it in WPF. I want to click and drag on a specific TextBlock in order to drag the window. Here is the code I've tried (I don't really know what I'm doing):

C#:
private void ProfileTextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
    drag = true;

    mousePoint = e.GetPosition(this);       

    mousex = mousePoint.X - this.Left;
    mousey = mousePoint.Y - this.Top;       
}

private void ProfileTextBlock_MouseMove(object sender, MouseEventArgs e)
{
    // stuff for dragging the form
    if (drag == true)
    {
        this.Top = mousePoint.Y - mousey;
        this.Left = mousePoint.X - mousex;
    }
}

private void ProfileTextBlock_MouseUp(object sender, MouseButtonEventArgs e)
{
    // stop dragging the form
    drag = false;
}

And here is the working WinForms code I tried to repurpose:

C#:
private void frmGCalc_MouseDown(object sender, MouseEventArgs e)
{
    // stuff for dragging the form
    drag = true;
    mousex = System.Windows.Forms.Cursor.Position.X - this.Left;
    mousey = System.Windows.Forms.Cursor.Position.Y - this.Top;
}

private void frmGCalc_MouseMove(object sender, MouseEventArgs e)
{
    // stuff for dragging the form
    if (drag == true) {
        this.Top = System.Windows.Forms.Cursor.Position.Y - mousey;
        this.Left = System.Windows.Forms.Cursor.Position.X - mousex;
    }
}

private void frmGCalc_MouseUp(object sender, MouseEventArgs e)
{
    // stop dragging the form
    drag = false;
}
 
As I recall telling you before, almost everything is done differently in WPF, so what ever you learned in WF, park it there, because it's likely not going to be any use to you in WPF.
 
Back
Top Bottom