禁用所有执行一段时间

时间:2012-04-02 08:32:21

标签: c# wpf

我需要在点击一个按钮后禁用所有事件的执行(单击)一段时间。在那个特定时期,无论我点击多少按钮,按钮的功能都不会被执行。我不能使用Thread.Sleep(),因为它只会延迟执行,按钮的功能仍在执行。 any1可以帮忙吗?我的代码在这里:

int delay = 2000; //unusable as it is just delaying the execution of clicked button.
public void PressCOM(string key)
    {
        if (key == "PressSc")
        { 
            PressAndRelease(key);
            PressAndRelease("C");

            Thread.Sleep(delay);
        }

4 个答案:

答案 0 :(得分:4)

无论如何,睡在主线上是个坏主意。

你必须建立一些关于按钮的逻辑:

  • 禁用它们
  • 忽略点击次数

使用由计时器重置的布尔属性。

答案 1 :(得分:2)

禁用并向用户显示“Please Wait ...”类型的消息将是更好的选择......

您可以根据需要在WPF中禁用和启用面板.Grids

我通常使用带有消息的Adorner Overlay(半透明)来阻止用户与UI进行交互...通常,Backround worker会在需要时帮助显示和隐藏叠加层。

This will be a Good Artice for Adorner implemtation in XAml

希望它有所帮助...... :)

答案 2 :(得分:2)

目前还不清楚你想做什么。

在主应用程序线程中进行睡眠并不是一个好主意。它将使您的应用程序不响应所有Windows消息(由用户或Windows本身发起)。您的用户将填充它。

如果您只需要停用该按钮,则可以将其IsEnabled属性设置为false,用户无法点击该属性。

如果您要停用所有事件,可以使用窗口本身的IsEnabled属性。

如果要禁用所有控件(或只有一个按钮)并不是适合您的解决方案,那么您可以使用以下方法之一。

添加状态变量(或简单标志)。在所有事件处理程序中,您将检查该变量是否为真(您将使用计时器更改它)。类似的东西:

if (!_canHandleMouseClicks)
   return false;

禁用所有按钮并在一段时间后重新启用它们:

private static IEnumerable<Button> FindAllButtons(DependencyObject obj)
{
    if (obj == null)
        return null;

    int childrenCount = VisualTreeHelper.GetChildrenCount(obj);
    for (int i = 0; i < childrenCount; ++i)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);

        if (child != null && child is Button)
            yield return (Button)child;

        // If you may have buttons inside buttons then uncomment these lines
        //foreach (Button childOfChild in FindAllButtons(child))
        //    yield return childOfChild;
    }
}

然后你可以写:

foreach (Button button in FindAllButtons(window))
    button.IsEnabled = false; // true to re-enable

答案 3 :(得分:0)

一种可能的解决方案可能是显示一个对话框并隐藏对话框,取消和关闭按钮。这样可以防止在主窗口中点击任何按钮。