简体   繁体   English

如何在 WinUI 3 应用程序中单击仅 3 秒后禁用按钮?

[英]How to disable a button after click for only 3 seconds in a WinUI 3 Application?

I have a button that I want to disable for 3 seconds so that it's not abused.我有一个按钮,我想禁用它 3 秒钟,以免它被滥用。 I wanted to add a Timer(3000);我想添加一个Timer(3000); inside the Click event however the example code I found is using outdated method and is not working.Click事件中,但是我发现的示例代码使用的是过时的方法并且无法正常工作。 I tried another code (which can be found below) however this throws System.Runtime.InteropServices.COMException: 'The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD))'我尝试了另一个代码(可以在下面找到)但是这抛出System.Runtime.InteropServices.COMException: 'The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD))' System.Runtime.InteropServices.COMException: 'The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD))' error. System.Runtime.InteropServices.COMException: 'The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD))'错误。

private void CodeButton_Click(object sender, RoutedEventArgs e)
{
    CodeButton.IsEnabled = false;
    var timer = new Timer(3000);
    timer.Elapsed += (timer_s, timer_e) =>
    {
            CodeButton.IsEnabled = true;
            timer.Dispose();

    };
    timer.Start();
    Launcher.LaunchUriAsync(new Uri("https://www.hoppie.nl/acars/system/register.html"));
}

You need to use the main thread (the thread that instantiated UI components) to update UI.您需要使用主线程(实例化 UI 组件的线程)来更新 UI。 You get that error because the timer will work with another thread, not the main thread.你得到那个错误是因为计时器将与另一个线程一起工作,而不是主线程。

You can do it this way:你可以这样做:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    try
    {
        // You can update the UI because
        // the Click event will use the main thread.
        this.Button.IsEnabled = false;

        List<Task> tasks = new();
        // The main thread will be released here until
        // LaunchUriAsync returns.
        tasks.Add(Launcher.LaunchUriAsync(new Uri("https://www.hoppie.nl/acars/system/register.html")));
        tasks.Add(Task.Delay(3000));
        await Task.WhenAll(tasks);
        // The main thread will be back here.
    }
    finally
    {
        // This will enable the button even if you face exceptions.
        this.Button.IsEnabled = true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM