C# – Redrawing during drag and drop

cdrag and dropnet

I would like trigger the drag target control to redraw itself (via either invalidate or refresh) during the DragEnter and DragLeave events. The code looks something like:

protected override void OnDragEnter (DragEventArgs drgargs)
{
  //-- Set a property that affects drawing of control, then redraw
  this.MyProperty = true;
  this.Refresh(); //-- Does nothing???      
}

protected override void OnDragLeave (EventArgs e)
{
  //-- Set a property that affects drawing of control, then redraw
  this.MyProperty = false;
  this.Refresh(); //-- Does nothing???      
}

It doesn't actually redraw the control, the OnPaint method is not called by the Refresh() within these events. Is there any way to do this? I must not be understanding something here.

UPDATE: the answer provided by jasonh doesn't actually work. When using Invalidate() or Invalidate(rect) the control does not actually update. This is being calls during a drag and drop action. Any other ideas? Can you trigger a redraw of a control during a drag and drop? Thanks!

UPDATE 2: I created a sample project and could not get this to not work. Sigh… I finally tracked it down to some code in the OnPaint that was causing the problem. So, this turned out to be more of me not understanding how the debugger worked (it never hit break points in the OnPaint…still don't know why). Invalidate(), Refresh() both work. JasonH gets the answer as it was ultimately correct and also showed how to invalidate just a portion of a control…I didn't know about that.

Thanks for all your help!

Best Answer

Call this.Invalidate() to get the Form/Control to redraw itself. If you know the specific region, then call one of the overloaded methods to specify what to invalidate. For example:

Rectangle toInvalidate = new Rectangle(drgargs.X - 50, drgargs.Y - 50, 50, 50);
this.Invalidate(toInvalidate);

That would invalidate an area 50 pixels around the area the drag target is.