hi i wanted to write a windows application that sends keyboard strokes to another application something like a virtual keyboard.

i researched the subject and read few articles.
i managed to find a code that partially works.

in the sample code above i'm trying to send strokes to a word file.
it workes partially in the first send and then it just stopps doing what it supposed to.

the code is:

// Get a handle to an application window.
        [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(string lpClassName,
            string lpWindowName);

        // Activate an application window.
        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

IntPtr wordHandle = FindWindow(null, "New Microsoft Word Document.doc - Microsoft Word");

            // Verify that word is a running process.
            if (wordHandle == IntPtr.Zero)
            {
                MessageBox.Show("wordis not running.");
                return;
            }

            // Make word the foreground application and send it 
            SetForegroundWindow(wordHandle);
            SendKeys.SendWait("111");
            SendKeys.SendWait("*");
            SendKeys.SendWait("11");
            SendKeys.SendWait("=");

any help will be appreciated.

Recommended Answers

It works for me except I had to add a call to sleep after SetForegroundWindow() . Also try adding a call to SendKeys.Flush() after you're done sending keystrokes:

SetForegroundWindow(wordHandle);
      System.Threading.Thread.Sleep(100);
      SendKeys.SendWait("111");
      SendKeys.SendWait("*");
      SendKeys.SendWait("11");
      SendKeys.SendWait("=");
      SendKeys.Flush();
Jump to Post

All 2 Replies

It works for me except I had to add a call to sleep after SetForegroundWindow() . Also try adding a call to SendKeys.Flush() after you're done sending keystrokes:

SetForegroundWindow(wordHandle);
      System.Threading.Thread.Sleep(100);
      SendKeys.SendWait("111");
      SendKeys.SendWait("*");
      SendKeys.SendWait("11");
      SendKeys.SendWait("=");
      SendKeys.Flush();

that works for me.
thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.