![](/img/trans.png)
[英]how to disable a button for two seconds after click and then enable itself again?
[英]How to disable a button after click for only 3 seconds in a WinUI 3 Application?
我有一个按钮,我想禁用它 3 秒钟,以免它被滥用。 我想添加一个Timer(3000);
在Click
事件中,但是我发现的示例代码使用的是过时的方法并且无法正常工作。 我尝试了另一个代码(可以在下面找到)但是这抛出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))'
错误。
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"));
}
您需要使用主线程(实例化 UI 组件的线程)来更新 UI。 你得到那个错误是因为计时器将与另一个线程一起工作,而不是主线程。
你可以这样做:
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.