Question

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.

Was it helpful?

Solution

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);           
    }

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top