如何在C#中创建选择工具

时间:2012-02-09 15:13:12

标签: c# winforms

Download the project

我正在尝试制作一个背景颜色的面板,当用户按住鼠标左键并移动它时,该面板应该能够在运行时绘制。所有作品都是在用户从左上角开始找到并向右下方移动,就像图像显示的那样:

但我希望用户能够从右下角到左上角制作面板。就像用鼠标选择计算机上的东西一样

Le Image

以下是我的代码:

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

我认为这是我出错的地方,我根本找不到合适的算法:

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

但是如果我使用矩形它工作正常,但我希望我的面板能够做到。

1 个答案:

答案 0 :(得分:3)

您只需检查起点的最小值和最大值与鼠标点的关系。代码的问题是您使用控件位置作为起点,但如果您将鼠标从右下角移动到左上角,则您的位置需要更改。控件的大小不能为负。

以下是我重新编写它的方法(我删除了不必要的测试内容):

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;
  }
}