开发者

Toggling Picture Box visibility C#

Why is the picture box control's visibility property not working here. I have initially set them to false, so that when the screen loads they are not visible. But then I wish to toggle this. I have done the following but does not seem to work. This is a windows forms application.

private void Action()
    {
        while (true)
        {

            Random r1 = new Random();
            int num = r1.Next(1,3);

            switch (num)
            {
                case 1:
                    pictureBoxLeft.Visible = true;
                    pictureBoxRight.Visible = true;
                    break;
                case 2:
                    pictureBoxLeft.Visible = true;
                    pictureBoxRight.Visible = false;
                    break;
                case 3:
                    pictureBoxLeft.Visible = false;
                    pictureBoxRight.Visible = true;
                    break;

            }

            Thread.Sleep(200);
            pictureBoxLeft.Visible = false;
            pictureBoxRight.Visible = false;
            Thread.Sleep(500);
        }
    }

Also to add, this is working properly with a text box!!! Any Ideas开发者_Python百科???

Many thanks in advance


Setting the Visible property to true doesn't show the control, it only creates a message that will show it. As long as you are keeping the main thread busy with a Sleep, it will not process any messages, and the controls won't be shown.

You should show the picture boxes and then set up a timer with code that will hide the picture boxes when the timer's tick event is triggered. Then you exit your method so that the main thread can handle the messages that will show the picture boxes.


This is your UI thread. UI thread is so busy that it is not getting time to refresh the display. UI thread is busy in endless while loop, so how can it update UI?


In addition to Thread.Sleep(); call Application.DoEvents() to trigger event handling/ui updating. However ensure you're not calling Action() again somehow. A simple Thread.Sleep() won't allow the UI to update as you're still in the handler and the framework won't be able fire any new events on its own as it won't know if you're finished when waiting (due to the thread still being busy).

Overall your approach might be a bad idea (depending on other code etc.). Consider using timers or a background worker instead.


Whenever the UI changes does not apear after you did some changes, always do Refres(). e.g. pictureBoxLeft.Refresh();. This will always make UI changes appear. Please let me know if it works for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜