0
I have an application in WPF that has no borders or background, it’s just a stylized button with an image and a frame, but I would like it to be possible to move it. My current code is like this:
<Button Name="button" Margin="10,130.475,377.541,10" Click="button_Click">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Rectangle Width="Auto" Margin="29.78,15.35,20.479,13.896" RenderTransformOrigin="0.5,0.5" Stroke="{x:Null}">
<Rectangle.Fill>
<ImageBrush ImageSource="img.png" Stretch="Uniform"/>
</Rectangle.Fill>
</Rectangle>
</ControlTemplate>
</Button.Template>
</Button>
//<...>
I tried this way, but I got no results
private void button_Click(object sender, RoutedEventArgs e)
{
DragMove();
//<...>
}
Edit: Following the answers, I adjusted this code to the application, however the movement only occurs with the right mouse and the left one does not generate any event.
private bool clicked = false;
private Point lmAbs = new Point();
void PnMouseDown(object sender, System.Windows.Input.MouseEventArgs e)
{
clicked = true;
this.lmAbs = e.GetPosition(this);
this.lmAbs.Y = Convert.ToInt16(this.Top) + this.lmAbs.Y;
this.lmAbs.X = Convert.ToInt16(this.Left) + this.lmAbs.X;
}
void PnMouseUp(object sender, System.Windows.Input.MouseEventArgs e)
{
clicked = false;
}
void PnMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (clicked)
{
Point MousePosition = e.GetPosition(this);
Point MousePositionAbs = new Point();
MousePositionAbs.X = Convert.ToInt16(this.Left) + MousePosition.X;
MousePositionAbs.Y = Convert.ToInt16(this.Top) + MousePosition.Y;
this.Left = this.Left + (MousePositionAbs.X - this.lmAbs.X);
this.Top = this.Top + (MousePositionAbs.Y - this.lmAbs.Y);
this.lmAbs = MousePositionAbs;
}
}
One way to get me to catch the event from the left mouse was by using the Previewmouseleftbuttondown, but then the window gets stuck to the cursor and I can’t release it.
use the onmousedown and onmouseup event associated with the button you want, and the associated onmousemove event on your screen, no down, mark a flag as true, no up, mark as false, no move, if the flag is true, move the screen along with the mouse
– Rovann Linhalis