Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 471
  • Last Modified:

Faking keyboard input

Is there a way I can create a program that will "fake" keyboard input to a window not owned by that program ? For example, can I make a program that will launch Notepad (with ShellExecute, or something), and then cause it to type "Foo" ?
0
Sinclair
Asked:
Sinclair
  • 4
  • 4
  • 3
  • +5
1 Solution
 
Andy_KeysCommented:
You could try and find the window handle and send messages to it.  Rather clunky I know.
0
 
fasterCommented:
The best way to fake keyboard input is keybd_event API.
0
 
fasterCommented:
Of course you need to make sure that the target window is the active window before using keybd_event.
0
 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

 
alexoCommented:
I humbly suggest using a journal playback hook as a more foolproof method.
0
 
SinclairAuthor Commented:
   Sorry, I am quite new at this. I saw the Journal Playback hook in the API docs, but it looks like I need to RECORD the keys first, somehow. I can't use that since I need to send an arbitrary sequence of keys.
    I also tried sending WM_KEYUP and WM_KEYDOWN messages, but they had absolutely no effect. What could I be doing wrong ?
0
 
fasterCommented:
did you try keybd_event()?
0
 
jjmartinCommented:
Using Visual Basic, you can create a program that will shell execute a program and then using the SendKey command you can send keystrokes to the application as if they were coming from the keyboard.  This is not as easy as it sounds.  You have to delay your sendkeys until the app is completely up.  You can also check the return code from the Shell command to close the app once you are done.
0
 
alexoCommented:
>> I saw the Journal Playback hook in the API docs, but it looks like I need to RECORD the keys first, somehow.

Not really.  You just have to fill the EVENTMSG structure with correct values.
0
 
SinclairAuthor Commented:
Ah, sorry, I still don't get it :-(
What's an EVENTMSG structure ? I was just using standard Win API. I know about the VB SendKeys function, that's what I am trying to replicate.
0
 
alexoCommented:
The EVENTMSG structure is what you use with a journalling playback hook.  It is usually filled by a journalling recording hook but you can do it yourself.  Check the SetWindowsHookEx() API.
0
 
akbCommented:
You could try a program called WinBatch.  There's a trial version available somewhere on the web.
0
 
SinclairAuthor Commented:
Thanks, I looked up the EVENTMSG structure. However, I still could not make the thing work. How do I prepare the lparam and wparam for the WM_KEY... messages ? And how do I get the "time" member of the structure ? Should I just use the current system time ? I understand that WinBatch works, but I would still like to implement the code myself. Is there any way this can be done ?
0
 
alexoCommented:
>> How do I prepare the lparam and wparam for the WM_KEY... messages ?
Check the documentation of the WM_KEYxxx messages.  It is comprehensive.

>> Should I just use the current system time ?
Sounds good enough.

0
 
vladimir_12345Commented:
Hi Sinclair!
This is a simple skileton that works (Win95, C).
 
#include <windows.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam,
                             LPARAM lParam);

void SendText(const char* Text);

#define CLASS   "KbdFake"
#define CAPTION "KbdFake"

#define NOTEPAD_TEXT "Foo"

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR
                   szCmdline, int iCmdShow)
{
 WNDCLASS wc;
 HWND     hwndMain;
 MSG      msg;

 wc.lpszClassName = CLASS;
 wc.hInstance     = hInst;
 wc.lpfnWndProc   = MainWndProc;
 wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
 wc.hIcon         = NULL;
 wc.lpszMenuName  = NULL;
 wc.hbrBackground = GetStockObject(LTGRAY_BRUSH);
 wc.style         = 0;
 wc.cbClsExtra    = 0;
 wc.cbWndExtra    = 0;
 if(!RegisterClass(&wc))
 {
  MessageBox(NULL, "Init Class Error.", CAPTION,
             MB_OK | MB_ICONSTOP);
  return FALSE;
 }

 hwndMain = CreateWindow(CLASS, CAPTION, WS_OVERLAPPEDWINDOW,
                         CW_USEDEFAULT, CW_USEDEFAULT,
                         CW_USEDEFAULT, CW_USEDEFAULT,
                         NULL, NULL, hInst, NULL);
 if(!hwndMain)
 {
  MessageBox(NULL, "Create Window Error.", CAPTION,
             MB_OK | MB_ICONSTOP);
  return FALSE;
 }

 ShowWindow(hwndMain, iCmdShow);
 UpdateWindow(hwndMain);

 while(GetMessage(&msg, NULL, 0, 0))
 {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
 }

 return TRUE;
}

LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam,
                             LPARAM lParam)
{
 switch(msg)
 {
  case WM_DESTROY:
  {
   PostQuitMessage(0);
   return 0;
  }

  case WM_RBUTTONDOWN:
  {
   if((int)ShellExecute(NULL, NULL, "NOTEPAD.EXE", NULL, NULL,
                        SW_SHOWNORMAL) <= 32)
    MessageBox(NULL, "ShellExecute() Error.", CAPTION,
               MB_OK | MB_ICONSTOP);

   while(GetForegroundWindow() == hwnd);

   SendText(NOTEPAD_TEXT);
   return 0;
  }
 }

 return DefWindowProc(hwnd, msg, wParam, lParam);
}

void SendText(const char* Text)
{
 int i;
 int Len = strlen(Text);

 for(i=0; i<Len; i++)
 {
  BOOL IsUpperKey     = isupper(Text[i]);
  BOOL IsCapsLockDown = GetKeyState(VK_CAPITAL);
  BOOL UseShift       = ( IsUpperKey  && !IsCapsLockDown) ||
                      (!IsUpperKey  &&  IsCapsLockDown);
  BYTE VirtKey        = toupper(Text[i]);
  BYTE ScanCode       = MapVirtualKey(VirtKey, 0);

  if(UseShift)
   keybd_event(VK_SHIFT, (BYTE)MapVirtualKey(VK_SHIFT, 0), 0, 0);

  keybd_event(VirtKey, ScanCode, 0, 0);
  keybd_event(VirtKey, ScanCode, KEYEVENTF_KEYUP, 0);

  if(UseShift)
   keybd_event(VK_SHIFT, (BYTE)MapVirtualKey(VK_SHIFT, 0),
               KEYEVENTF_KEYUP, 0);
 }
}

0
 
SinclairAuthor Commented:
Hi,
  How to simulate "ctrl+alt+del" sequence to start winnt login with user intervention. Above piece of code works for all key combination except this one.
0
 
shankar_msCommented:
Hi Shankar_ms! WIN works in the next sequence:
kbd interrupt -> kbd driver -> keybd_event() -> kbd message

"ctrl+alt+del" is processed in kbd driver only (system level) and
doesn't go to keybd_event() (there is no kbd message for this
key combination). I think to simulate "ctrl+alt+del" you have
to use kbd driver service.


0
 
vladimir_12345Commented:
Hi vladmir

Do you know how to doit? I am new to keyboard driver?

ThANKS
Shankar
0
 
shankar_msCommented:
I work in Win95/98 and have no info about NT "ctrl+alt+del".
But I think you will not have a big problem to find anything
suitable in Internet. In the other side if you can find WIN NT
API call that have at the same result as "ctrl+alt+del"- this is
a better way.

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 4
  • 3
  • +5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now