Click here to Skip to main content
15,886,724 members
Articles / Desktop Programming / Win32
Tip/Trick

Easy way to simulate keyboard press and release keys

Rate me:
Please Sign up or sign in to vote.
4.92/5 (4 votes)
6 Mar 2013CPOL1 min read 57.5K   2.5K   18   2
An easy way to simulate keyboard press & release keys to another application

Introduction

This article describes an easy way to simulate keyboard press and release keys to another application. It uses the SendInput API for simulating keyboard press and release keys.

To illustrate this technique we will show how to automatically run calc.exe and simulate add x and y and get the result back.

Application Latching

We will run the application using the CreateProcess API and save the process ID to close it.

C++
void startProcess(DWORD &processPid,char*mProcess)
{
 BOOL bWorked;
 STARTUPINFO suInfo;
 PROCESS_INFORMATION procInfo;
 memset (&suInfo, 0, sizeof(suInfo));
 suInfo.cb = sizeof(suInfo);
 bWorked = ::CreateProcess(mProcess,
      NULL,  
      NULL,
      NULL,
      FALSE,
      NORMAL_PRIORITY_CLASS,
      NULL,
      NULL,
      &suInfo,
      &procInfo);
 if (procInfo.dwThreadId = NULL)
 {
 }
 processPid = procInfo.dwProcessId;
}

Making the application in foreground

Retrieves a handle to the top-level window whose window name matches the AppName using FindWindow, then activate the application using SetForegroundWindow so the Keyboard input is directed to the window .

C++
HWND windowHandle = FindWindow(0, AppName);
if(windowHandle == NULL)
{
    return -1;
}
SetForegroundWindow(windowHandle); 

Simulate keyboard press and release keys

Using SendChar, SendInt, SendText based on the SendInput Windows API, we will simulate keyboard press and release keys.

C++
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
ip.ki.wVk = CHAR_ID;
//For key press Flag=0
ip.ki.dwFlags = 0;
SendInput(1, &ip, sizeof(INPUT));
//For key relese Flag = KEYEVENTF_KEYUP
ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));

Simulation sequence

First send x then + then Y and press Enter, then copy the result in Clipboard using Ctrl+C.

C++
SendInt(x);
Sendchar(VK_ADD);
SendInt(y);
Sendchar(VK_RETURN);    

PressKey(VK_CONTROL);
Sendchar('C');
ReleseKey(VK_CONTROL);  

Retrieve the Result from Clipboard

Using GetClipboardData, retrieve the result from the Clipboard.

C++
int GetClipboardText(char*ClipboardText)
{
    HANDLE clip;
    if (OpenClipboard(NULL))
    {
        clip = GetClipboardData(CF_TEXT);
        sprintf(ClipboardText,"%s",clip);
        return 0;
    }
    return -1;
}

Closing the application

Enumerate all windows using the EnumWindowsProc callback function, passing the PID of the process you started earlier.

C++
void killProcess(DWORD processPid)
{
  Sleep(100);
  HANDLE ps = OpenProcess( SYNCHRONIZE|PROCESS_TERMINATE,
                    FALSE, processPid);
  EnumWindows(EnumWindowsProc, processPid);
  CloseHandle(ps) ;
}

Then in EnumWindowsProc, send the WM_CLOSE message to close it.

C++
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
  Sleep(1);
  DWORD wndPid;
  char Title[1024];
  // This gets the windows handle and pid of enumerated window.
  GetWindowThreadProcessId(hwnd, &wndPid);
  // This gets the windows title text
  // from the window, using the window handle
  GetWindowText(hwnd,Title,1024);
  // this makes sure that the PID matches that PID we started, and window
  // text exists, before we kill it . I don't think this is really needed,
  // I included it because some apps have more than one window.
  if ( wndPid == (DWORD)lParam && strlen(Title) != 0)
  {
    // Please kindly close this process
    ::PostMessage(hwnd, WM_CLOSE, 0, 0);
    //cout<<"Please kindly close this process"<<endl;
    return false;
  }
  else
  {
    //cout<<"Keep enumerating"<<endl;
    // Keep enumerating
    return true;
  }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Egypt Egypt
بسم الله الرحمن الرحيم
وَنَزَعۡنَا مَا فِى صُدُورِهِم مِّنۡ غِلٍّ۬ تَجۡرِى مِن تَحۡتِہِمُ ٱلۡأَنۡہَـٰرُ‌ۖ وَقَالُواْ ٱلۡحَمۡدُ لِلَّهِ ٱلَّذِى هَدَٮٰنَا لِهَـٰذَا وَمَا كُنَّا لِنَہۡتَدِىَ لَوۡلَآ أَنۡ هَدَٮٰنَا ٱللَّهُ‌ۖ لَقَدۡ جَآءَتۡ رُسُلُ رَبِّنَا بِٱلۡحَقِّ‌ۖ وَنُودُوٓاْ أَن تِلۡكُمُ ٱلۡجَنَّةُ أُورِثۡتُمُوهَا بِمَا كُنتُمۡ تَعۡمَلُونَ 
صدق الله العظيم

In the name of Allah, the Beneficent, the Merciful
"And We remove whatever rancour may be in their hearts. Rivers flow beneath them. And they say: The praise to Allah, Who hath guided us to this. We could not truly have been led aright if Allah had not guided us. Verily the messengers of our Lord did bring the Truth. And it is cried unto them: This is the Garden. Ye inherit it for what ye used to do. (43)"

Comments and Discussions

 
Questionبارك الله فيك Pin
imedmaamria1-May-14 9:41
imedmaamria1-May-14 9:41 
AnswerRe: بارك الله فيك Pin
Ahmed Elkafrawy8-May-14 7:08
Ahmed Elkafrawy8-May-14 7:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.