Tamir said:
I have a couple of objects(eg. Rectangles) for dragging them I'm using
double buffering, and it works fine while using only one of them. Once I'
trying to put another object on screen the first one is disapperas and
there is flicking while draggings.
Please advice.
I'm assuming you're talking about a Windows Forms application here?
When you say you have a couple of objects, what exactly do you mean? Do you
mean multiple controls? Or just that you're drawing multiple features?
It's very hard to work out what the problem might be with your very brief
description - I have no idea what your code is doing. But here's an example
that shows lots of draggable rectangles, all of which can be dragged around
without any flicker whatsoever:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace DragRectangles
{
public class DragRectangles : System.Windows.Forms.Form
{
private Rectangle[] rectangles = new Rectangle[10];
public DragRectangles()
{
Text = "Rectangles";
SetStyle(ControlStyles.DoubleBuffer |
ControlStyles.AllPaintingInWmPaint, true);
Random rand = new Random();
for (int i = 0; i < rectangles.Length; ++i)
{
rectangles
= new Rectangle(
rand.Next(Width - 100), rand.Next(Height - 100),
rand.Next(100) + 10, rand.Next(100) + 10);
}
}
protected override void OnPaint(PaintEventArgs e)
{
using (Brush b = new SolidBrush(Color.FromArgb(30,
Color.DarkBlue)))
using (Pen p = new Pen(Color.Black, 2))
{
for (int i = 0; i < rectangles.Length; ++i)
{
e.Graphics.FillRectangle(b, rectangles);
e.Graphics.DrawRectangle(p, rectangles);
}
}
base.OnPaint (e);
}
private bool dragging = false;
private int rectangleBeingDragged;
private int dragPrevX, dragPrevY;
protected override void OnMouseDown(MouseEventArgs e)
{
for (int i = 0; i < rectangles.Length; ++i)
{
if (rectangles.Contains(e.X, e.Y))
{
dragging = true;
dragPrevX = e.X;
dragPrevY = e.Y;
rectangleBeingDragged = i;
break;
}
}
base.OnMouseDown (e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
dragging = false;
base.OnMouseUp (e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (dragging)
{
int dx = e.X - dragPrevX;
int dy = e.Y - dragPrevY;
Rectangle original = rectangles[rectangleBeingDragged];
rectangles[rectangleBeingDragged].Location += new Size(dx,
dy);
Rectangle updateArea =Rectangle.Union(original,
rectangles[rectangleBeingDragged]);
updateArea.Inflate(1,1);
Invalidate(updateArea);
dragPrevX = e.X;
dragPrevY = e.Y;
}
base.OnMouseMove (e);
}
[STAThread]
static void Main()
{
Application.Run(new DragRectangles());
}
}
}