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

查看:501
本文介绍了使用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具有特殊含义.指定以下一项 这些字符,将其括在大括号({})中.例如, 指定加号,使用"{+}".要指定大括号字符,请使用 {{}"和 "{}}".方括号([])对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);

测试

我已经测试了代码,并且进行了在线测试,可以查看正则表达式[+^%~()]

  • 输入:加号+插入符^百分比波浪号〜父母()
  • 输出加{+}插入符{^}百分比{%}波浪{〜}父母{{} {)}
  • Input: Plus + Caret ^ Percent % Tilde ~ Parenthis ( )
  • Output Plus {+} Caret {^} Percent {%} Tilde {~} Parenthis {(} {)}

这篇关于使用SendKeys发送特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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