Java Prüfen ob Leertaste gedrückt wird Wie geht das Bitte um antwort
Hallo Leute,
ich habe ein Problem: Ich wollt wenn die Leertaste gedrückt wird, eine Variable um eins erhöhen und weiß nicht wie es geht. Ich habe schon gegoogelt, habe aber nur sehr lange code gefunden und habe nix durchgeblickt. In VB oder C++ braucht man max 5 Zeilen und es kann nicht sein, dass man für Java ca. 50 braucht.
Bitte um Antwort
HUND999
3 Antworten
Um zu überprüfen, ob eine Taste gerückt wurde, musst du den KeyListener in deine Klasse einbinden, der dann verschiedene Funktionen dafür bereitstellt. In den nachfolgenden Beispiel wurde der KeyListener an ein JFrame gebunden. Achte darauf, dass die Events nur ausgelöst werden, wenn dein JFrame den Focus hat:
public class MyFrame extends JFrame implements KeyListener
{
public MyFrame()
{
this.addKeyListener(this);
}
public void keyPressed(KeyEvent E)
{
if (String.valueOf(E.getKeyChar()) == ' ')
{
// Leertaste wurde gedrückt
}
}
public void keyTyped(KeyEvent E)
{
}
public void keyReleased(KeyEvent E)
{
}
}
http://openbook.galileocomputing.de/javainsel/
Ich programmier ab und an auch Java, aber manches muß man einfach nachlesen... ;-)
Ganz einfach:
HWND notepad = FindWindow(T(InputHandler), NULL); HWND edit = FindWindowEx(notepad, NULL, T("IHD"), NULL); SendMessage(edit, WMSETTEXT, NULL, (LPARAM)T("stroke")); INPUT *keystroke; UINT i, charactercount, keystrokestosend, keystrokes_sent; HWND notepad;
assert( text != NULL ); IHadler= FindWindow( _T( "IH" ), NULL ); if( handler== NULL ) return 0;
if( !SetForegroundWindow( notepad ) ) return 0;
character_count = _tcslen( text ); keystrokes_to_send = character_count * 2; keystroke = new INPUT[ keystrokes_to_send ]; for( i = 0; i < character_count; ++i ) { keystroke[ i * 2 ].type = INPUT_KEYBOARD; keystroke[ i * 2 ].ki.wVk = 0; keystroke[ i * 2 ].ki.wScan = text[ i ]; keystroke[ i * 2 ].ki.dwFlags = KEYEVENTF_UNICODE; keystroke[ i * 2 ].ki.time = 0; keystroke[ i * 2 ].ki.dwExtraInfo = GetMessageExtraInfo();
keystroke[ i * 2 + 1 ].type = INPUT_KEYBOARD;
keystroke[ i * 2 + 1 ].ki.wVk = 0;
keystroke[ i * 2 + 1 ].ki.wScan = text[ i ];
keystroke[ i * 2 + 1 ].ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
keystroke[ i * 2 + 1 ].ki.time = 0;
keystroke[ i * 2 + 1 ].ki.dwExtraInfo = GetMessageExtraInfo();
}
keystrokes_sent = SendInput( ( UINT )keystrokes_to_send, keystroke, sizeof( *keystroke ) ); delete [] keystroke;
return keystrokes_sent == keystrokes_to_send;
}
Using SendMessage():
int SendKeystrokesToNotepad( const TCHAR *const text ) { HWND notepad, edit;
assert( text != NULL );
notepad = FindWindow( _T( "Notepad" ), NULL ); if( notepad == NULL ) return 0;
edit = FindWindowEx( notepad, NULL, _T( "Edit" ), NULL ); if( edit == NULL ) return 0;
SendMessage( edit, EM_REPLACESEL, ( WPARAM )TRUE, ( LPARAM )text ); return 1;
}
credits to Notch