使用 SendKeys 发送特殊字符 [英] Send special character with SendKeys

查看:39
本文介绍了使用 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 发送特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆