【问题标题】:Drag and drop rectangle in C#在 C# 中拖放矩形
【发布时间】:2011-01-27 09:05:43
【问题描述】:

我想知道如何在 C# 中绘制矩形并将其拖放到页面中,我的代码来绘制它,但我无法拖放它。

public partial class Form1 : Form
{
    public bool drag = false;
    int cur_x, cur_y;
    Rectangle rec = new Rectangle(10, 10, 100, 100);
    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs r)
    {
        base.OnPaint(r);
        Graphics g = r.Graphics;
        //g.DrawRectangle(Pens.Black, rec);
        g.FillRectangle(Brushes.Aquamarine, rec);

    }
    private void recmousedown(object sender, MouseEventArgs m)
    {
        if (m.Button != MouseButtons.Left)
            return;
        rec = new Rectangle(m.X, m.Y,100,100);

        drag = true;
        cur_x = m.X;
        cur_y = m.Y;
    }

    private void recmousemove(object sender, MouseEventArgs m)
    {
        if (m.Button != MouseButtons.Left)
            return;

       rec.X = m.X;
       rec.Y = m.Y;
       Invalidate();
    }
}

【问题讨论】:

  • 我认为你需要多说一下这里“拖放”的确切含义:使用绘画的技术将产生一次性矩形,这些矩形将在下一次 MouseDown 时被清除对 Invalidate 的调用。您是否正在寻找一个矩形或将“持续”在屏幕上的矩形?然后您可以“选择”并四处移动或调整大小?
  • 如果您需要“形状”,请查看当前的 SO 问题:stackoverflow.com/questions/2440912/…

标签: c# system.drawing


【解决方案1】:

你已经很接近了,你只需要更好地初始化矩形并在 Move 事件中调整矩形大小:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      this.DoubleBuffered = true;
    }
    Rectangle rec = new Rectangle(0, 0, 0, 0);

    protected override void OnPaint(PaintEventArgs e) {
      e.Graphics.FillRectangle(Brushes.Aquamarine, rec);
    }
    protected override void OnMouseDown(MouseEventArgs e) {
      if (e.Button == MouseButtons.Left) {
        rec = new Rectangle(e.X, e.Y, 0, 0);
        Invalidate();
      }
    }
    protected override void OnMouseMove(MouseEventArgs e) {
      if (e.Button == MouseButtons.Left) {
        rec.Width = e.X - rec.X;
        rec.Height = e.Y - rec.Y;
        Invalidate();
      }
    }
  }

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多