控件上的C#跨线程SendToBack / BringToFront操作

时间:2022-07-18 10:58:43

I am developing a card game. I have represented cards with PictureBox class. I have a game where players put cards one on top of another, one by one. Z-index of all these cards are different and when card is put on top i give it top z-index with this code:

我正在开发一款纸牌游戏。我用PictureBox类代表了卡片。我有一个游戏,玩家将卡片一个接一个地放在另一个上面。所有这些卡的Z-index是不同的,当卡放在顶部时,我用这段代码给它顶部的z-index:

PictureBox cardPictureBox = move.Card.CardPictureBox;
if (cardPictureBox.InvokeRequired) 
    cardPictureBox.Invoke(new MethodInvoker(cardPictureBox.BringToFront));

This code works fine and all cards are brought to front when they supposed to. I have a problem when this game ends. That is when I need to put PictureBox objects back to their original place. I put them back but they are now not ordered as I ordered them in Designer. I have to rearrange their z-indexes. I do this with the same code, but in a loop where I do the same thing for every card.

这段代码工作正常,并且所有卡片在他们应该的时候被带到前面。这场比赛结束时我遇到了问题。那时我需要将PictureBox对象放回原来的位置。我把它们放回去,但是现在它们没有订购,因为我在Designer中订购它们。我必须重新安排他们的z索引。我使用相同的代码执行此操作,但是在循环中我为每张卡执行相同的操作。

Program doesn't throw an exception but just freezes and that's it!?!?! Did someone encounter this problem, and does it has an answer?

程序不会抛出异常而只是冻结,就是这样!!!?!有人遇到这个问题,它有答案吗?

How can I make a safe cross-thread change of PictureBox z-index without my program freezing?

如何在没有程序冻结的情况下对PictureBox z-index进行安全的跨线程更改?

Thanks in advance

提前致谢

1 个解决方案

#1


0  

Simplest way would be to skip the invoke when you're doing them all in a loop at the end:

最简单的方法是在最后一个循环中完成所有操作时跳过调用:

foreach (CardPictureBox cardPB in Collection) 
{
    cardPB.BringToFront();
}

#1


0  

Simplest way would be to skip the invoke when you're doing them all in a loop at the end:

最简单的方法是在最后一个循环中完成所有操作时跳过调用:

foreach (CardPictureBox cardPB in Collection) 
{
    cardPB.BringToFront();
}