Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag a WPF Form around the desktop

i am trying to make a c# WPF form where i can drag it around the screen by clicking on it and moving with the mouse. the forms characteristics include being completely transparent and containing only one image. This being said the window style is none and it is not displayed in the taskbar. So essentially all you can see when the app is running is a little image - and ideally i want to be able to drag it around the desktop if i click and hold the left mouse button and move it about.

Does anyone know a simple way i can accomplish this or have i overlooked a build in function?

Thanks.

like image 314
Grant Avatar asked May 15 '09 05:05

Grant


3 Answers

Previous answers hit on the answer, but the full example is this:

   private void Window_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            DragMove();
        }
    }
like image 144
EPiddy Avatar answered Oct 26 '22 15:10

EPiddy


You can use the Window.DragMove method in the mouse down event of the window.

like image 33
Josh Avatar answered Oct 26 '22 15:10

Josh


Here is some simplified code to drag the WPF form around your screen. You might have seen some of this code on different posts, I just modified it to fit the needs of dragging the WPF form.

Keep in mind we need to grab the form position on the MouseLeftButtonDown, so we can keep the mouse pointer positioned in the same spot on the form as we are dragging it around the screen.

You will also need to add the following reference to get the mouse position relative to the screen: System.Windows.Forms

Properties Needed:

private bool _IsDragInProgress { get; set; }
private System.Windows.Point _FormMousePosition {get;set;}

Code:

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            this._IsDragInProgress = true;
            this.CaptureMouse();
            this._FormMousePosition = e.GetPosition((UIElement)this);
            base.OnMouseLeftButtonDown(e);
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (!this._IsDragInProgress)
                return;

            System.Drawing.Point screenPos = (System.Drawing.Point)System.Windows.Forms.Cursor.Position;
            double top = (double)screenPos.Y - (double)this._FormMousePosition.Y;
            double left = (double)screenPos.X - (double)this._FormMousePosition.X;
            this.SetValue(MainWindow.TopProperty, top);
            this.SetValue(MainWindow.LeftProperty, left);
            base.OnMouseMove(e);
        }

        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            this._IsDragInProgress = false;
            this.ReleaseMouseCapture();
            base.OnMouseLeftButtonUp(e);
        }
like image 39
TheMiddleMan Avatar answered Oct 26 '22 15:10

TheMiddleMan