简体   繁体   English

从C#应用程序向Java应用程序发送击键-奇怪的行为吗?

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

I'm trying to send keystrokes from my C# program to a Java application 我正在尝试将击键从C#程序发送到Java应用程序

The code for sendig keys is: sendig密钥的代码为:

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. 这段代码适用于所有程序,但我要控制的Java应用程序除外。

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. 这会将F2发送到主程序窗口,然后弹出另一个窗口,第二个SendKeysToWindow命令将“ 123”发送到该窗口。 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. 但是,当我将这些命令发送到Java程序时,会发生以下情况:第一个SendKeysToWindow命令执行得很好(出现弹出窗口),但不会将“ 123”发送到该窗口。

If is press the button again, the "123" is sent to the popup window, and it opens another popoup window. 如果再次按下该按钮,则会将“ 123”发送到弹出窗口,并打开另一个弹出窗口。

If I create two separate buttons for the two SendKeysToWindow command, and press them one after another, both commands execute fine. 如果我为两个SendKeysToWindow命令创建两个单独的按钮,然后一个接一个地按下它们,则两个命令都可以正常执行。

What can be the probem? 什么是探针?

Thanks for the help in advanvce, it's really driving me crazy. 感谢您提供的帮助,这确实使我发疯。

PS: I'm a beginner in C#, so please keep the answer simple. PS:我是C#的初学者,所以请简单回答。

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. 听起来好像在发送{f2}与Java应用程序打开弹出窗口之间可能会有延迟。

Have you tried checking whether FindWindow succeeds or fails? 您是否尝试过检查FindWindow成功还是失败?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM