Reputation: 4089
I'm currently developing a C# application. Right now I'm trying to realize a simple slider:
|--------------------------|
| |
| |--------------------| |
| | | |
| | Panel1 | |
| | Panel2 | |
| | | |
| |--------------------| |
| x x x |
|--------------------------|
I have two panels with exactly the same size. Panel1 is just needed for displaying a border and setting the boundaries for panel2 which is then dynamically exchanged.
If the second x is clicked, panel2 should move to the left and panel3 should come from the right and also move to the left.
Basically I have the following code:
Panel panel2 = panelArray[0];
Panel panel3 = panelArray[1];
The following code should now perform the slide:
for (int i = 0; i <= 100; i++)
{
panel2.Location = new Point(panel2.Location.X - i, panel2.Location.Y);
System.Threading.Thread.Sleep(10);
}
for (int i = 0; i <= 100; i++)
{
panel3.Location = new Point(100 - i, panel3.Location.Y);
System.Threading.Thread.Sleep(10);
}
Somehow the first panel is slided-out perfectly but panel2 is not sliding. It's just displayed after the loop is executed.
Any idea why panel2 isn't performing the slide? I'm using WinForms.
Upvotes: 0
Views: 3018
Reputation: 60236
The problem is that you're not allowing the message pump to run by forcing a sleep. The suggested Application.DoEvents
triggers the message pump, but it isn't a good solution because your code still blocks most of the time and you may even run in infinite loops with this pattern (e.g. if DoEvents
re-enters the event you're calling it from).
Instead of using Thread.Sleep
you should rather use a (Winforms) Timer
. This will solve the UI update problem and also keep the UI alive while the slider moves.
Upvotes: 0
Reputation: 2792
Try adding Application.DoEvents
in the body of your loop after the location change. The UI needs a chance to catch up.
Upvotes: 1