views:

349

answers:

2

Hi.

I'm trying to send keystrokes from my C# program to a Java application

The code for sendig keys is:

private void SendKeysToWindow(string WindowName, string KeysToSend)
    {
        IntPtr hWnd = FindWindow(null, WindowName);
        ShowWindowAsync(hWnd, SW_SHOWNORMAL);
        SetForegroundWindow(hWnd);
        SendKeys.Send(KeysToSend);            
    }

This code works fine with all programs, except with the Java application that I'm tyring to control.

For example, if I create a button with the folowing code:

SendKeysToWindow("Java application window name", "{F2}");
SendKeysToWindow("Popoup window name", "123");

This sends an F2 to the main program window, where another window pops up, and the second SendKeysToWindow command sends the "123" to that window. This is how it is expected to work, and this is the case with all other programs.

However, when I send these commands to the Java program, the following happens: the first SendKeysToWindow command is executed fine (the popup window appears), but it does not send the "123" to that window.

If is press the button again, the "123" is sent to the popup window, and it opens another popoup window.

If I create two separate buttons for the two SendKeysToWindow command, and press them one after another, both commands execute fine.

What can be the probem?

Thanks for the help in advanvce, it's really driving me crazy.

P.S.: I'm a beginner in C#, so please keep the answer simple.

A: 

It sounds like there might just be a delay between sending {f2} and the Java application opening the popup window.

Have you tried checking whether FindWindow succeeds or fails?

Blorgbeard
When I click on the button for the second time, it immediately writes the "123" to the first popup window. I cannor even see it, because the second popup window hides it immediately, so the delay cannot be much more than in windows programs.I tried to add a Thread.Sleep between the two SendKeysToWindow commands, but without success.I'll try both ShowWindow instead of ShowWindowAsync and checking FindWindow success.What about using SendWait instead of send?
Miklós
+1  A: 

After some trial and error, the following code seems to work fine:

private void SendKeysToWindow(string WindowName, string KeysToSend)
    { 
        IntPtr hWnd = FindWindow(null, WindowName);            
        ShowWindow(hWnd, SW_SHOWNORMAL);
        SetForegroundWindow(hWnd);
        Thread.Sleep(50);
        SendKeys.SendWait(KeysToSend);           
    }
Miklós