I might be missing something obvious, and forgive me if I am.
Anyways, I have a class Keys
which has method SPrintScreen
as follows:
class Keys{
uint32_t sentQM;
// create array to be passed to SendInput function
INPUT printscreen[2];
// set both types to keyboard events
printscreen[0].type = INPUT_KEYBOARD;
printscreen[1].type = INPUT_KEYBOARD;
// assign printscreen key
printscreen[0].ki.wVk = VK_SNAPSHOT;
printscreen[1].ki.wVk = VK_SNAPSHOT;
// add key up flag to second input
printscreen[1].ki.dwFlags = KEYEVENTF_KEYUP;
void SPrintScreen(){
sentQM = SendInput(2, printscreen, sizeof(INPUT));
if (sentQM != ARRAYSIZE(printscreen)){
std::cout << "could not simulate print screen" << std::endl;
}
}
}
When I create the Keys
object on the stack (Keys keys;
) then call SPrintScreen
( keys.SPrintScreen() ), things work as expected, and the pressing of the print screen key is simulated and the program can continue running.
However when I create the Keys
object on the heap (Keys* keys;
), and call SPrintScreen
( keys->SPrintScreen() )the program just silently exits without any indication of why, not even a message in the console.
How is this working only sometimes?
CodePudding user response:
Keys* keys;
does not create a Keys object. It creates a pointer to a keys object. In order do something you have to do 2 more things
- create a Keys objects
- point
keys
at it
Like this
Keys *keyObj = new Keys();
keys = keyObj;
obviously you would actually do
Keys *keys = new Keys();
This makes a Keys object on the heap. Alternatively, you could have one on the stack
Keys mykeys;
Keys *keys = &mykeys;
Which works for you depends on what you are trying to do. Also try not to have naked pointers for heap objects, use shared_ptr or unique_ptr