简体   繁体   中英

Draggable WPF window with no border

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?

Use the tunneled MouseDown event, ie, 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(); };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM