Search code examples
c#winformspinvokesendkeys

Sending letter 'i' with SendKeys


I made an on screen keyboard with c# Windows Forms. I use Sendkeys.Send() function to send the keystrokes. All letters but the letter i works fine. When I press the letter i on the keyboard when Microsoft Word is open, it sends Ctrl + Alt + I and opens the print dialog. It is same in Notepad++ as well. But it works fine when I try to type in notepad.

In my code I send the keys with SendKeys.Send(value); where value is the text of the button which is pressed. I get the text with the following code:

string s = ((Button)sender).Text;

Any comments about why it does not work properly?

Edit: I have created a new windows forms project with just a button and the whole code is below. Still not working. Any idea would be appreciated.

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SendKeys.Send("i");
        }

        // Prevent form being focused
        const int WS_EX_NOACTIVATE = 0x8000000;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams ret = base.CreateParams;
                ret.ExStyle |= WS_EX_NOACTIVATE;
                return ret;
            }
        }  
    }

The overridden function is to prevent the form being focused. So that I can send the keystrokes to the other application which has the focus.


Solution

  • Two alternatives:

    1- Simulates a keypress, see http://msdn2.microsoft.com/en-us/library/system.windows.forms.sendkeys(VS.71).aspx

    Sample:

    public static void ManagedSendKeys(string keys)
            {
                SendKeys.SendWait(keys);
                SendKeys.Flush();
            }
    

    2- Sends a key to a window, pressing the button for x seconds

    [DllImport("user32.dll")]
    public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
    public static void KeyboardEvent(Keys key, IntPtr windowHandler, int delay)
            {
                const int KEYEVENTF_EXTENDEDKEY = 0x1;
                const int KEYEVENTF_KEYUP = 0x2;
                keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);
                Thread.Sleep(delay);
                keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
            }