C# 如何实现稳定的SendKeys功能 解决脱字符后字符全小写问题
SendKeys发送脱字符后后续字符全小写问题解决方案
问题根因
.NET 内置SendKeys类存在修饰键状态处理缺陷:即使你将特殊字符脱字符^通过正则转义为{^}发送,其内部的修饰键状态标记会出现异常复位,导致后续大写字母对应的Shift模拟触发逻辑失效,最终所有大写字母全部输出为小写。
修复方案(无第三方依赖)
推荐使用逐字符独立处理的方案,彻底隔离特殊字符导致的全局状态异常,稳定性最高:
public static void AutoTypeText(string text) { foreach (char c in text) { string sendContent = c switch { // 转义所有SendKeys内置特殊字符 '+' or '^' or '%' or '~' or '(' or ')' or '{' or '}' or '[' or ']' => $"{{{c}}}", // 大写字母单独转义,避免状态异常导致Shift按键触发失败 >= 'A' and <= 'Z' => $"{{{c}}}", // 普通字符直接输出 _ => c.ToString() }; SendKeys.Send(sendContent); // 若存在输入过快漏字问题,可打开下方注释增加小幅延迟 // Thread.Sleep(1); } }
如果使用低于C# 8的版本,可将switch表达式替换为if判断实现相同逻辑:
public static void AutoTypeText(string text) { foreach (char c in text) { string sendContent; if ("+^%~(){}[]".Contains(c)) { sendContent = $"{{{c}}}"; } else if (c >= 'A' && c <= 'Z') { sendContent = $"{{{c}}}"; } else { sendContent = c.ToString(); } SendKeys.Send(sendContent); } }
额外优化建议
如果输入场景对稳定性要求极高,可以将SendKeys.Send替换为SendKeys.SendWait,等待系统完成当前按键处理后再发送下一个字符,进一步降低漏字、错字概率。
内容的提问来源于stack exchange,提问作者Jerry Philips
相关产品推荐
相关产品推荐

