C#实现Excel自动关闭并点击不保存时的空值警告消除求助
解决关闭Excel自动点击“Don't Save”时的空值警告
一、处理FindWindow代码的CS8625警告
警告原因
FindWindow(null, "Microsoft Excel")中传递的null与函数声明里的非可空string参数不兼容,触发CS8625警告。
修复方案
修改FindWindow及FindWindowEx的DllImport声明,将参数类型改为可空引用类型string?,允许传递null值:
[DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string? lpClassName, string? lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string? className, string? windowTitle);
修改后传递null参数不会触发警告,同时保留原有功能逻辑。
二、处理UI Automation代码的CS8600警告
警告原因
button.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern可能返回null,但赋值给了非可空的InvokePattern变量,触发CS8600警告。
修复方案
将InvokePattern变量声明为可空类型InvokePattern?,适配as转换可能返回null的情况:
static void InvokeButton(AutomationElement button) { InvokePattern? invokePattern = button.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern; invokePattern?.Invoke(); }
同时修正原代码中FindExcelWindow的逻辑错误(ProcessIdProperty对应整数类型进程ID,而非字符串),避免功能失效:
static AutomationElement FindExcelWindow() { string excelClassName = "XLMAIN"; var excelProcesses = System.Diagnostics.Process.GetProcessesByName("EXCEL"); if (excelProcesses.Length == 0) return null; foreach (var proc in excelProcesses) { PropertyCondition classCondition = new PropertyCondition(AutomationElement.ClassNameProperty, excelClassName); PropertyCondition processCondition = new PropertyCondition(AutomationElement.ProcessIdProperty, proc.Id); AndCondition condition = new AndCondition(classCondition, processCondition); var window = AutomationElement.RootElement.FindFirst(TreeScope.Children, condition); if (window != null) return window; } return null; }
内容的提问来源于stack exchange,提问作者administr4tor
相关产品推荐
相关产品推荐

