示例代码如下:
// 创建一个OpenFileDialog示例
var openFileDialog = new OpenFileDialog();
// 注册CancelButtonClicked回调函数
openFileDialog.CancelButtonClicked += (sender, args) =>
{
Console.WriteLine("Cancel button was clicked.");
};
// 创建一个SaveFileDialog示例
var saveFileDialog = new SaveFileDialog();
// 注册CancelButtonClicked回调函数
saveFileDialog.CancelButtonClicked += (sender, args) =>
{
Console.WriteLine("Cancel button was clicked.");
};
示例代码如下:
// 创建一个CancellationTokenSource示例
var cts = new CancellationTokenSource();
// 创建一个OpenFileDialog示例,并将CancellationTokenSource实例传递给它
var openFileDialog = new OpenFileDialog(cts.Token);
// 调用ShowAsync方法,此时可以在其他线程中检测CancellationTokenSource是否已被取消
var result = await openFileDialog.ShowAsync();
if (cts.IsCancellationRequested)
{
Console.WriteLine("Cancel button was clicked.");
}
else if (result.Length > 0)
{
Console.WriteLine($"Selected file: {result[0]}");
}
// 创建一个SaveFileDialog示例,并将CancellationTokenSource实例传递给它
var saveFileDialog = new SaveFileDialog(cts.Token);
// 调用ShowAsync方法,此时可以在其他线程中检测CancellationTokenSource是否已被取消
var result = await saveFileDialog.ShowAsync();
if (cts.IsCancellationRequested)
{
Console.WriteLine("Cancel button was clicked.");
}
else if (result != null)
{
Console.WriteLine($"Selected file: {result}");
}
注意:为了使CancellationTokenSource实例在用户关闭对话框时得到释放,必须在使用之后及时清理(调用Dispose方法)。