简体   繁体   中英

Drag & drop event for WinForms Form not Control

What I'm trying to do.

I have searching if there exists a drag&drop event for a System.Windows.Forms.Form class without luck...

I was wondering if there is an optimized way of doing this...


What I have done so far.

I have been doing the following thing:

    private Rectangle WinBar
    {
        get
        {
            return new Rectangle(Location.X, Location.Y, Width, 31);
        }
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left && WinBar.Contains(e.Location))
            Console.WriteLine("Being dragged!");
    }

My purpouse is that if the IF-statment is true I will call an EventHandler .


My main questions

But, for now, I can't figure this out, because of the following reasons:

  • If I move the Form to the upper left corner of the screen negative values appear. I suppose this is not a problem, but I don't know why e.Location is not equal to (0, 0) if I put the Form in exact corner.
  • When my mouse is over the WinForm Bar nothing appears , but if I move the mouse under (like 30 pixels to the left and 50 px to the bottom) the console goes crazy.
  • Why there isn't a native EventHandler for this case?

Why I used 31 pixels for the WinBar height

I have checked that WinForms when FormBorderStyle property is set to FormBorderStyle.FixedSingle or Fixed3D or FixedSingle or Sizable is 31 pixels, as this image show us:

证据

The evidence is on the size of the selection on MSPaint .

But I not use how to measure it for example for FixedToolWindow or SizableToolWindow . (Maybe I should use a ternary condition)


So, there are several uncertain things, and I don't know if this is the better way to do it. So, any help would be great!

Thanks in advance!

If I understand you correctly, you are trying to sense when the whole form is moved around the screen, right?

If so, use the Form´s LocationChanged event and examine the Form´s Location property to see where you are...

Edit to add example:

using System;
using System.Windows.Forms;

namespace WindowsFormsTestMove
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_LocationChanged(object sender, EventArgs e)
        {
            var loc = this.Location;
            this.Text = loc.X + " " + loc.Y;
        }
    }
}

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