How to make a selection tool in C #

Download project

I am trying to make a panel with a background color that should be available at runtime when the user holds the left mouse button and moves it. All work is detected when the user starts from the upper left position and goes to the lower right, as shown in the figure:

But I want the user to be able to make a panel from bottom right to top left. Just like when you select something on your computer with the mouse

Le Image

Here is my code:

public void parent_MouseMove(object sender, MouseEventArgs e)
{
  if (e.Button == System.Windows.Forms.MouseButtons.Left)
  {
    Point tempLoc = e.Location;
    this.Location = new Point
    (
      Math.Min(this.Location.X, tempLoc.X),
      Math.Min(this.Location.Y, tempLoc.Y)
    );

    this.Size = new Size
    (
      Math.Abs(this.Location.X - tempLoc.X),
      Math.Abs(this.Location.Y - tempLoc.Y)
    );

    this.Invalidate();
  }
}

I think I'm wrong here and I just can't find the right algorithm for it:

this.Size = new Size
(
  Math.Abs(this.Location.X - tempLoc.X),
  Math.Abs(this.Location.Y - tempLoc.Y)
);

But if I use a rectangle, it works fine, but I want my panel to be able to do this too.

+5
source share
1 answer

mousemoving. , , , . .

( ):

public class SelectionTool : Panel {
  Form parent;
  Point _StartingPoint;

  public SelectionTool(Form parent, Point startingPoint) {
    this.DoubleBuffered = true;
    this.Location = startingPoint;

    //this.endingPoint = startingPoint;
    _StartingPoint = startingPoint;

    this.parent = parent;
    this.parent.Controls.Add(this);
    this.parent.MouseMove += new MouseEventHandler(parent_MouseMove);
    this.BringToFront();
    this.Size = new Size(0, 0);
  }

  public void parent_MouseMove(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Left) {
      int minX = Math.Min(e.Location.X, _StartingPoint.X);
      int minY = Math.Min(e.Location.Y, _StartingPoint.Y);
      int maxX = Math.Max(e.Location.X, _StartingPoint.X);
      int maxY = Math.Max(e.Location.Y, _StartingPoint.Y);
      this.SetBounds(minX, minY, maxX - minX, maxY - minY);

      this.Invalidate();
    }
  }

  protected override void OnPaint(PaintEventArgs e) {
    base.OnPaint(e);
    this.BackColor = Color.Blue;
  }
}

, :

private SelectionTool _SelectPanel = null;

private void Form1_MouseMove(object sender, MouseEventArgs e) {
  if (e.Button == System.Windows.Forms.MouseButtons.Left) {
    if (_SelectPanel == null)
      _SelectPanel = new SelectionTool(this, e.Location);
  }
}

private void Form1_MouseUp(object sender, MouseEventArgs e) {
  if (_SelectPanel != null) {
    _SelectPanel.Dispose();
    _SelectPanel = null;
  }
}
+3

All Articles