WinForms 任务对话框
在 WinForms 中使用 Vista 任务对话框 - 这里提供了一些代码来实现它。
引言
Vista 新的任务对话框 API 非常棒,应该取代您应用程序中那些过时的消息框。我们已经看到了一些关于从 C++ 使用它们的文章,但从托管代码使用它们并不简单,所以这里提供了一些代码,可以轻松地在 WinForms 中使用新的任务对话框的所有功能。
代码是用 C# 编写的,并且通过 StyleCop、FXCop 和 PreSharp 检查过,保证代码质量。易用性和可发现性优先于性能和大小,并包含大量注释,这些注释在您探索任务对话框的功能时,在 Intellisense 中会非常有用。您不必使用任何带有大写字母命名的东西,并且任务对话框的所有功能都已公开,包括您可以在活动的任务对话框上执行的回调和操作。如果您讨厌包装器,并且想要原始的互操作声明,它们也都在那里。
使用代码
主要的类是 TaskDialog
。最简单的用法可以获得消息框的行为
TaskDialog taskDialog = new TaskDialog();
taskDialog.WindowTitle = "My Application";
taskDialog.MainInstruction = "Do you want to do this?";
taskDialog.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;
int result = taskDialog.Show();
if (result == (int)DialogResult.Yes)
{
// Do it.
}
从那里您可以添加用于帮助的超链接,更多的结构(将内容、扩展信息和页脚添加到主指令),用于“不再询问我”的复选框,自定义按钮名称等。
private void SampleUsageComplex()
{
TaskDialog taskDialog = new TaskDialog();
taskDialog.WindowTitle = "My Application";
taskDialog.MainInstruction = "Do you want to do this?";
taskDialog.EnableHyperlinks = true;
taskDialog.Content = "If you do this there could be all sorts of consequences. " +
"If you don't there will be other consequences. " +
"You can <A HREF=\"Learn\">learn more about those consequences </A> or more " +
"about <A HREF=\"blah\">blah blah blah</A>.";
taskDialog.Callback = new TaskDialogCallback(this.MyTaskDialogCallback);
taskDialog.VerificationText = "Don't ask me this ever again.";
taskDialog.VerificationFlagChecked = false;
TaskDialogButton doItButton = new TaskDialogButton();
doItButton.ButtonId = 101;
doItButton.ButtonText = "Do It";
TaskDialogButton dontDoItButton = new TaskDialogButton();
dontDoItButton.ButtonId = 102;
dontDoItButton.ButtonText = "Don't Do It";
taskDialog.Buttons = new TaskDialogButton[] { doItButton, dontDoItButton };
bool dontShowAgain;
int result = taskDialog.Show(null, out dontShowAgain);
if (dontShowAgain)
{
// Suppress future asks.
}
if (result == doItButton.ButtonId)
{
// Do it.
}
}
private bool MyTaskDialogCallback(
ActiveTaskDialog taskDialog,
TaskDialogNotificationArgs args,
object callbackData)
{
if (args.Notification == TaskDialogNotification.HyperlinkClicked)
{
if (args.Hyperlink.Equals("Learn", StringComparison.Ordinal))
{
// Show a help topic.
}
else if (args.Hyperlink.Equals("blah", StringComparison.Ordinal))
{
// Show a different help topic.
}
}
return false;
}
要更好地了解 TaskDialog
的所有功能,下载演示,将 TaskDialogTest.exe 和 TaskDialog.dll 提取到同一目录,并运行 TaskDialogTest.exe。您将获得一个相当大的对话框,虽然它可能不够美观,但可以让您尝试任务对话框,并可能了解不同用途在您的应用程序中的外观。
要在您自己的解决方案中使用 TaskDialog
,下载源代码并将以下源代码文件包含在您的项目中,并根据需要进行调整
- ActiveTaskDialog.cs
- TaskDialog.cs
- TaskDialogNotificationArgs.cs
- UnsafeNativeMethods.cs
或者,您可以将 TaskDialog 项目包含到您的解决方案中。
我期待在您的应用程序中看到更少的消息框,并希望这能使其更容易。在使用所有这些功能在一个对话框中时,请记住良好的 UI 设计。