Reynevan Reynevan - 2 months ago 18
C# Question

Converting a string into SendKeys.Send() formatted string

Is there any smart and neat way to I guess escape characters in a

string
to make it compatible with the specific format the
SendKeys
uses?

At first I thought this would work:

line = Regex.Replace(line, @"\{{0}", "{{}");
line = Regex.Replace(line, @"\}{0}", "{}}");


But this won't work work because it's doing two checks and messes up the syntax entirely.

How can I handle this?

Answer

You can use some place holder instead of { and } and create the formatted result using those place holders. Then at last replace those place holders by { and }. For example:

string PrepareForSendKeys(string input)
{
    var specialChars = "+^%~(){}";
    var c1 = "[BRACEOPEN]";
    var c2 = "[BRACECLOSE]";
    specialChars.ToList().ForEach(x =>
    {
        input = input.Replace(x.ToString(),
            string.Format("{0}{1}{2}", c1, x.ToString(), c2));
    });
    input = input.Replace(c1, "{");
    input = input.Replace(c2, "}");
    return input;
}

And you can use it this way:

var input = "some string containing + ^ % ~ ( ) { }";
MessageBox.Show(PrepareForSendKeys(input));

And the result would be:

some string containing {+} {^} {%} {~} {(} {)} {{} {}}