c++ Program to take a screenshot

rsthegreat12 picture rsthegreat12 · Jul 27, 2014 · Viewed 15.6k times · Source

I am making a program that will click the printscreen key of the keyboard. The code I am using is the following:

INPUT myInput;

myInput.type = INPUT_KEYBOARD;

KEYBDINPUT keyboardInput;
keyboardInput.wScan = 0;
keyboardInput.dwFlags = 0;
keyboardInput.time = 0;
keyboardInput.dwExtraInfo = 0;
keyboardInput.wVk = VK_SNAPSHOT; 
myInput.ki = keyboardInput;

SendInput(1, &myInput, sizeof(INPUT));//pressing the printscreen key

keyboardInput.dwFlags = KEYEVENTF_KEYUP;
myInput.ki = keyboardInput;

SendInput(1, &myInput, sizeof(INPUT));//releasing the printscreen key

for some reason the code doesn't work what so ever. If I go to paint and try to paist from clipboard, it will only past whatever printscreen I had done before I had used my program. Also my keyboard doesn't need me to press the "alt" with the print screen in order for it to work..

I had tryed to included the pressing of the Alt key beeeforee the pressing of the printscreen key, as well as the release of the Alt key afffftterr the releasing of the printscreen key, and the difference I got was that when I tried to past it on paint, I paist some kind of a full black screen... This was just a test I did to see if it makes a difference, but my actual keyboard takes screenshots with only the hit of the print screen button.

Any ideas on what I am doing wrong guys?

Edited: just to let you guys know, the program does in fact compile. I have also added other code that saves the clipboard file to a directory, and I do save a file correctly if I manually hit the print screen button... but if I keep looping this code with the saving to a directory, the same picture of the manually obtained screenshot appears... so that is how I know for sure that there is a problem with the hitting of the printscreen button.

Answer

Software_Designer picture Software_Designer · Aug 2, 2014

On the windows platform: You have to follow a certain sequence of simulated key presses.

The code below is a simulates keybd_event() keyboard events and puts the captured screen into the clipboard.

#include <iostream>
#include <windows.h>
using namespace std;



int main()
{
    keybd_event(VK_MENU, 0, 0, 0); //Alt Press
    keybd_event(VK_SNAPSHOT, 0, 0, 0); //PrntScrn Press


    keybd_event(VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0); //PrntScrn Release
    keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0); //Alt Release

return 0;
}