Sending keystrokes from a C# application to a Java application - strange behaviour?

风流意气都作罢 提交于 2020-01-04 14:18:29

问题


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.


回答1:


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



回答2:


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?



来源:https://stackoverflow.com/questions/2038730/sending-keystrokes-from-a-c-sharp-application-to-a-java-application-strange-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!