Send special character with SendKeys(使用 SendKeys 发送特殊字符)
问题描述
我正在使用文本框通过 SendKeys 发送文本,但是当我在文本框中插入特殊字符时,我的应用程序崩溃了.例如,当我在文本框中输入+"时,我收到此错误:SendKeys 字符串+"无效.
I am using textboxes to send text via SendKeys, but when I insert special characters in the textbox, my application crashes. For example, when I put in a '+' in the textbox, I get this error: SendKeys string '+' is not valid.
我需要一个使用 SendKeys 发送特殊字符的解决方案,这是我的代码的一部分:
I need a solution to send special characters with SendKeys, this is a part of my code:
SendKeys.Send(dropDownEffectsLeft1.SelectedItem.ToString() + dropDownEffectsRight1.SelectedItem.ToString() + txt1.Text);
这都是关于名为 txt1
我想我需要像 Regex 这样的东西来检查我的 txt 是否包含任何特殊字符,我会这样做:
I think I need something like a Regex to check if my txt contains any special characters, and that I will do with:
Regex specialChar = new Regex(@"^[a-zA-Z0-9_@.-]*$");
非常感谢您的帮助.
推荐答案
来自 MSDN 发送密钥:
加号 (+)、插入符号 (^)、百分号 (%)、波浪号 (~) 和括号 () 对 SendKeys 有特殊含义.指定其中之一将这些字符括在大括号 ({}) 中.例如,要指定加号,使用{+}".要指定大括号字符,请使用{{}"和{}}".方括号 ([ ]) 对 SendKeys 没有特殊意义,但是您必须将它们括在大括号中.在其他应用中,括号确实具有特殊含义,当动态数据时可能很重要发生交换 (DDE).
The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses () have special meanings to SendKeys. To specify one of these characters, enclose it within braces ({}). For example, to specify the plus sign, use "{+}". To specify brace characters, use "{{}" and "{}}". Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces. In other applications, brackets do have a special meaning that might be significant when dynamic data exchange (DDE) occurs.
代码
所以你只需要一个正则表达式来替换这些字符:
Code
So you just need a regex to replace those characters:
string txt = Regex.Replace(txt1.Text, "[+^%~()]", "{$0}");
SendKeys.Send(txt);
测试
我测试了代码,我有一个在线测试,你可以检查一下正则表达式 [+^%~()]
- 输入:Plus + Caret ^ Percent % Tilde ~ Parenthis ( )
- 输出 加号 {+} 插入符号 {^} 百分比 {%} 波浪号 {~} 括号 {(} {)}
这篇关于使用 SendKeys 发送特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 SendKeys 发送特殊字符
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
