C# SendKeys.Send

42,786

Solution 1

I solved this problem by registering global hot keys. Thank you. This was the resourse that I used to solve my problem.

Solution 2

I would reverse my calls:

SendKeys.Send("{BS}");

SendKeys.Send("S");

EDIT (After Question Updated):

If you're working with the string (for your special characters), can you not just capture the string generated by the key press ("a") and modify it by setting the string to the unicode value of the character you're attempting to represent? If the other solutions people have been mentioning aren't working, that's where I'd try next...

Solution 3

I might be making a bad assumption, but if you are using this with a text box, you could:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 'a')
    {
        e.Handled = true;
    }
}

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
    {
        e.Handled = true;
        SendKeys.Send("s");
    }
}

Or even simpler:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 'a')
    {
        e.Handled = true;
        SendKeys.Send("s");
    }
}

Or if this isn't for use just with a text box, then can't you just revers your backspace and s key sends?

if ((Keys)keyCode== Keys.A)
{                    
    SendKeys.Send("{BS}"); // remove A
    SendKeys.Send("s");    // add S
}

Solution 4

Another option you have is to use Low-Level keyboard hooks to trap the old character and then send the new one. It will require some P/Invoke, but it gives you the ability to completely trap the original key so apps don't even see it.

Solution 5

I get "a" printed because backspace is sent immediately after "s" and it deletes the "s" character. How can I prevent this from happening?

uhm.....

don't send backspace immediately after sending s?

if ((Keys)keyCode== Keys.A)
            {
                Sendkeys.Send("{BS}"); // Deletes the "A" (already sent)
                SendKeys.Send("s"); // Sends the "S"
            }
Share:
42,786
MrHetii
Author by

MrHetii

Updated on July 29, 2020

Comments

  • MrHetii
    MrHetii almost 4 years

    I am running on an issue using C# SendKeys.Send method. I am trying to replace keyboard keys with other keys, for example when I press "a" in keyboard I want that key to be "s" for example, when I am doing this in my code:

    if ((Keys)keyCode== Keys.A)
    {                    
        SendKeys.Send("s");                    
    
    }
    

    Right now I get only "sa" character printed in my notepad, but instead of printing "sa" I need to get only "s" character in this case because when I press "a" on my keyboard, "a" must be replaced with "s".

    I tried removing the last character by adding this line:

    SendKeys.Send("{BS}");
    

    But all I got is "s" character removed and "a" character was there.

    How can I prevent this from happening?