Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draggable WPF window with no border

Tags:

c#

wpf

draggable

I'm using WindowStyle=None to remove the border of a WPF window. In the MainWindow.xaml.cs file I just added the following line to the constructor:

this.MouseLeftButtonDown += delegate { this.DragMove(); };

This somewhat works and lets me drag the window around wherever I left click inside the MainWindow, as long as it's not on any control. Because that's where I get problems. I have a textbox that takes up all the space inside the window, and as soon as I do this I can no longer move the window around when left clicking inside the textbox.

How can I make the window move around if the user left clicks inside the window and drags the mouse no matter what control the user is hitting?

Or simpler, how can I make the window move when the user left clicks and drags inside the textbox control?

like image 329
Daniel Jørgensen Avatar asked Jan 03 '16 20:01

Daniel Jørgensen


1 Answers

Use the tunneled MouseDown event, i.e, the PreviewMouseLeftButtonDown event of the Window. This will ensure that the event occurs both on the Window and its child controls:

this.PreviewMouseLeftButtonDown += (s, e) => DragMove();

You can also add an event to the TextBox manually:

textBox.MouseDown += (s, e) => DragMove();

But:

Doing what you want has its inherent problems. It will not let you select text in the TextBox. There is a workaround - use a Key + MouseDrag input like this:

bool isKeyPressed = false;

public MainWindow()
{
    InitializeComponent();
    this.PreviewKeyDown += (s1, e1) => { if (e1.Key == Key.LeftCtrl) isKeyPressed = true; };
    this.PreviewKeyUp += (s2, e2) => { if (e2.Key == Key.LeftCtrl) isKeyPressed = false; };
    this.PreviewMouseLeftButtonDown += (s, e) => { if (isKeyPressed) DragMove(); };
}
like image 126
Fᴀʀʜᴀɴ Aɴᴀᴍ Avatar answered Sep 22 '22 15:09

Fᴀʀʜᴀɴ Aɴᴀᴍ