开发者

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

开发者 https://www.devze.com 2022-12-16 03:25 出处:网络
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)

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 SendKeysToW开发者_Go百科indow 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.


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消