Draggable WPF window without frame

I use WindowStyle=None to remove the border of a WPF window. In the MainWindow.xaml.cs file, I simply added the following construct to the constructor:

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

This works somewhat and allows me to drag the window to where I left the click inside MainWindow, if it is not on any control. Because I'm having problems. I have a text box 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 you click in the text box.

How can I make the window move if the user left clicks inside the window and drags the mouse, no matter which control he clicks?

Or easier, how can I make the window move when the user leaves the clicks and drags inside the text box control?

+5
source share
1 answer

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

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

You can also add an event to the text box manually:

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

But

Doing what you want has its inherent problems. This will not allow you to select text in a TextBox. There is a workaround - use the Key + MouseDrag as follows:

 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(); }; } 
+3
source

Source: https://habr.com/ru/post/1239743/


All Articles