【问题标题】:Sending a Keyboard Input with Java JNA and SendInput()使用 Java JNA 和 SendInput() 发送键盘输入
【发布时间】:2015-02-16 09:30:17
【问题描述】:

我有兴趣在本例中使用 java 与操作系统进行交互,在这种情况下是 windows 7,并希望在低级别上模拟一些击键(例如 CTRL + V)。

首先我知道 java 是一个糟糕的选择,但它是我最好的编程语言,我知道它是可能的。 另外我知道 awt.robot 存在,但它对我来说太高了(我真的需要驱动程序级别)。

我问这个问题是因为我真的很想了解 jna 并且在看了 20 个代码示例之后我仍然遇到问题。

一个由 sendInput() 完成的击键的代码示例对我很有帮助。

非常感谢。

问候 Ext1nc1on

【问题讨论】:

  • 请使用您自己的代码示例添加您已经尝试过的内容。另外,当你说你仍然有问题时,是什么问题?

标签: java jna keystroke sendinput


【解决方案1】:

如果有人对 JNA SendInput 仍有问题,请查看以下示例:

import com.sun.jna.Native;
import com.sun.jna.platform.win32.BaseTSD;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;

/**
 * Created by Vellotis on 2.02.2016.
 */
public class User32Test
{
    public static void main( String[] args )
    {
        // Loop all windows
        User32.INSTANCE.EnumWindows(( hWnd, data ) -> {
            char[] name = new char[512];

            User32.INSTANCE.GetWindowText( hWnd, name, name.length );

            // Find window with title starting with downcase "keyb" string
            if ( Native.toString( name ).toLowerCase().startsWith( "keyb" ) )
            {
                // Bring the window to the front
                User32.INSTANCE.SetForegroundWindow( hWnd );

                // Prepare input reference
                WinUser.INPUT input = new WinUser.INPUT(  );

                input.type = new WinDef.DWORD( WinUser.INPUT.INPUT_KEYBOARD );
                input.input.setType("ki"); // Because setting INPUT_INPUT_KEYBOARD is not enough: https://groups.google.com/d/msg/jna-users/NDBGwC1VZbU/cjYCQ1CjBwAJ
                input.input.ki.wScan = new WinDef.WORD( 0 );
                input.input.ki.time = new WinDef.DWORD( 0 );
                input.input.ki.dwExtraInfo = new BaseTSD.ULONG_PTR( 0 );

                // Press "a"
                input.input.ki.wVk = new WinDef.WORD( 'A' ); // 0x41
                input.input.ki.dwFlags = new WinDef.DWORD( 0 );  // keydown

                User32.INSTANCE.SendInput( new WinDef.DWORD( 1 ), ( WinUser.INPUT[] ) input.toArray( 1 ), input.size() );

                // Release "a"
                input.input.ki.wVk = new WinDef.WORD( 'A' ); // 0x41
                input.input.ki.dwFlags = new WinDef.DWORD( 2 );  // keyup

                User32.INSTANCE.SendInput( new WinDef.DWORD( 1 ), ( WinUser.INPUT[] ) input.toArray( 1 ), input.size() );

                return false; // Found
            }

            return true; // Keep searching
        }, null );
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    相关资源
    最近更新 更多