即时通讯使用keybd_event();我想使用SendMessage();将按键发送到记事本,可以这样做吗?
答案 0 :(得分:8)
使用SendMessage
将文本插入编辑缓冲区(听起来像你想要的那样):
HWND notepad = FindWindow(_T("Notepad"), NULL);
HWND edit = FindWindowEx(notepad, NULL, _T("Edit"), NULL);
SendMessage(edit, WM_SETTEXT, NULL, (LPARAM)_T("hello"));
如果你需要密钥代码和任意键击,你可以使用SendInput()
(2k / xp和首选),或keybd_event()
`(这将最终在较新的操作系统中调用SendInput)这里的一些例子:
http://www.codeguru.com/forum/showthread.php?t=377393
还有您可能感兴趣的SendMessage的WM_SYSCOMMAND / WM_KEYDOWN / WM_KEYUP / WM_CHAR事件。
答案 1 :(得分:6)
keybd_event()已被SendInput()取代,因此最好使用它。以下是一些示例代码,可以执行您所要求的操作。您可以使用SendMessage()直接编辑记事本窗口的编辑控件,也可以使用SendInput()来合成要发送到窗口的击键。
使用SendInput()
:
int SendKeystrokesToNotepad( const TCHAR *const text )
{
INPUT *keystroke;
UINT i, character_count, keystrokes_to_send, keystrokes_sent;
HWND notepad;
assert( text != NULL );
//Get the handle of the Notepad window.
notepad = FindWindow( _T( "Notepad" ), NULL );
if( notepad == NULL )
return 0;
//Bring the Notepad window to the front.
if( !SetForegroundWindow( notepad ) )
return 0;
//Fill in the array of keystrokes to send.
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();
}
//Send the keystrokes.
keystrokes_sent = SendInput( ( UINT )keystrokes_to_send, keystroke, sizeof( *keystroke ) );
delete [] keystroke;
return keystrokes_sent == keystrokes_to_send;
}
int SendKeystrokesToNotepad( const TCHAR *const text )
{
HWND notepad, edit;
assert( text != NULL );
//Get the handle of the Notepad window.
notepad = FindWindow( _T( "Notepad" ), NULL );
if( notepad == NULL )
return 0;
//Get the handle of the Notepad window's edit control.
edit = FindWindowEx( notepad, NULL, _T( "Edit" ), NULL );
if( edit == NULL )
return 0;
SendMessage( edit, EM_REPLACESEL, ( WPARAM )TRUE, ( LPARAM )text );
return 1;
}
我希望有所帮助。