Search code examples
c#animationmdichild

Two MDI child forms interfering with each other


I am writing an MDI application in C# that contains two child forms which are referenced through DLL (stand alone projects added to references). One child form (call it form1) is performing animation based on graphic objects using a timer. This project (child form1) works fine until the other child form (call it form2) is loaded. What happens is that animation on the first form (form1) stops, but when I close this second child form (form2) animation continues with no problem.

I use this code in form2:

private void FlyingBeeForm_Paint(object sender, PaintEventArgs e) {
    Graphics g = e.Graphics; 
    DrawImages(g); 
    System.Threading.Thread.Sleep(50); 
    this.Invalidate(); 
}

Solution

  • The timer is kept going by a notification delivered by Windows when the interval has expired. It is however a very low priority notification, you'll only get it when no other work needs to be done.

    You now should see the problem with your Paint event handler. For one, you prevent any work from getting done by sleeping constantly. Then you ensure there's always work to be done by calling Invalidate(). So Windows generates a new paint event and never gets around to the state where a timer event can be delivered.

    You must remove the Sleep and Invalidate call. And use a 50 msec timer instead. Just call Invalidate() in its Tick event handler.