Button.Visible = true;无法在功能内激活时将按钮设置为可见 [英] Button.Visible = true; fails to set the button to visible when activated within a function

查看:123
本文介绍了Button.Visible = true;无法在功能内激活时将按钮设置为可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到有同样问题的其他人,所以希望有人可能有一些想法,或者能够指出我另一个答案。

I haven't been able to find anyone else having this same problem, so hopefully someone might have some ideas or be able to point me to another answer.

当通过按表单上的按钮运行函数时,另一个按钮应该可见。但是,该按钮从不显示,即使它是功能中的第一件事。

When a function is run by pressing a button on the form, another button should become visible. However, the button never shows up even though it is the first thing in the function. All of the other code in the function works perfectly.

这是代码:

private void trackbar_Change(object sender, EventArgs e)
{
    button.Visible = true;
    progressbar.Visible = true;

    ...

    progressbar.Visible = false;
    button.Visible = false;
}

进度条显示并正常工作,函数中的所有其他代码

The progress bar shows up and works fine, and all other code in the function works fine as well, but the button never shows up at all.

如果我删除 button.Visible = false; 从函数结束,然后按钮DOES显示,但只有在所有其他代码已执行后。像这样:

If I remove button.Visible = false; from the end of the function, then the button DOES show up, but only after all other code has executed. Like this:

private void trackbar_Change(object sender, EventArgs e)
{
    button.Visible = true;
    progressbar.Visible = true;

    ...

    progressbar.Visible = false;
    //button.Visible = false;
}

注释掉该行会导致按钮显示。现在如果我在按钮行后添加一个消息框,那么它也工作。

Commenting out that line causes the button to show up. Now if I add a message box after the button line, then it also works.

private void trackbar_Change(object sender, EventArgs e)
{
    button.Visible = true;
    MessageBox.Show("Button should be visible now");
    progressbar.Visible = true;

    ...

    progressbar.Visible = false;
    button.Visible = false;
}

在按钮行后添加消息框导致按钮显示在正确的时间。

Adding the message box after the button line caused the button to show up at the right time.

有没有人有什么想法为什么这个按钮是这样的行为?

Does anyone have any ideas why this button is behaving this way?

推荐答案

这听起来像GUI线程很忙。尝试强制更新屏幕,方法是调用 Application.DoEvents( ),例如:

It sounds like the GUI thread is busy. Try forcing the screen update by calling Application.DoEvents(), for example:

button.Visible = true;
progressbar.Visible = true;
Application.DoEvents();

DoEvents()

更好的解决方案将移动主UI线程的长时间运行的线程。对任务使用 BackgroundWorker

A better solution would be to move the long running thread of main UI thread. Use a BackgroundWorker for the task.

这将使表单更具响应性。例如,你将能够与表单交互,它不会变成白色。实现BackgroundWorker是简单的,并且是主UI线程上长时间运行的进程必须的,

It will make the form more responsive overall. For example you would be able to interact with the form and it won't turn 'white'. Implementing the BackgroundWorker is simple and a must for long running processes on the main UI thread,

这篇关于Button.Visible = true;无法在功能内激活时将按钮设置为可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆