using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppMessageBox { public static class ErrorHandler { publicstaticvoidShowError(Exception ex, string context = "") { string errorMessage = string.IsNullOrEmpty(context) ? $"发生错误: {ex.Message}" : $"在{context}时发生错误: {ex.Message}"; MessageBox.Show( errorMessage, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1 ); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppMessageBox { public partial class Form1 : Form { publicForm1() { InitializeComponent(); } privatevoidbtnReadFile_Click(object sender, EventArgs e) { try { // 文件读取操作 string content = File.ReadAllText("config.txt"); } catch (Exception ex) { ErrorHandler.ShowError(ex, "读取配置文件"); } } } }
⚠️ 常见坑点:不要在错误信息中暴露过多技术细节,用户看不懂反而会增加困扰。
🎨 技巧2:用户操作确认的最佳实践
应用场景:删除数据、退出程序、保存更改等不可逆操作
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppMessageBox { public static class ConfirmationHelper { publicstaticboolConfirmDangerousAction(string actionName, string details = "") { string message = string.IsNullOrEmpty(details) ? $"确定要{actionName}吗?此操作无法撤销!" : $"确定要{actionName}吗?\n\n详细信息:{details}\n\n此操作无法撤销!"; DialogResult result = MessageBox.Show( message, "操作确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2 // 默认选中"否",更安全 ); return result == DialogResult.Yes; } } }
💎 金句总结:默认按钮永远选择最安全的选项,让用户需要主动确认危险操作。
🔄 技巧3:多步骤操作的进度反馈
应用场景:批量处理、长时间操作的中断处理
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppMessageBox { public class BatchProcessor { publicvoidProcessFiles(string[] filePaths) { for (int i = 0; i < filePaths.Length; i++) { try { ProcessSingleFile(filePaths[i]); } catch (Exception ex) { DialogResult result = MessageBox.Show( $"处理文件 '{Path.GetFileName(filePaths[i])}' 时出错:\n{ex.Message}\n\n是否继续处理其余文件?", $"批处理错误 ({i + 1}/{filePaths.Length})", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1 ); if (result == DialogResult.No) break; // 停止处理 elseif (result == DialogResult.Cancel) return; // 取消整个操作 // Yes:继续处理下一个文件 } } MessageBox.Show("批处理完成!", "操作完成", MessageBoxButtons.OK, MessageBoxIcon.Information); } privatevoidProcessSingleFile(string filePath) { // 模拟文件处理逻辑 if (new Random().Next(0, 3) == 0) // 随机抛出异常以模拟错误 { thrownew Exception("模拟处理错误"); } } } }