Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

winapi - Simulate a KeyEvent in C

I wanted to simulate some actions in a game. When I start the programm it should just simulate some Keys getting pressed. It worked for e.g. text editor, but not for the abilites in the game. Like for example pressing 1 is a normal attack. Any way to solve this?

#include <windows.h>

INPUT ip;

void simulate_key_press(int number, int sleep_time){
  ip.ki.wVk = 0x30 + number;
  ip.ki.dwFlags = 0;
  SendInput(1, &ip, sizeof(INPUT));
  ip.ki.dwFlags = KEYEVENTF_KEYUP;
  SendInput(1, &ip, sizeof(INPUT));
  Sleep(sleep_time);
}

void play_part(int* p_sleep_time, int* p_note, int amount_notes, int sleep_pause){
  for(int i = 0; i < amount_notes; i++){
    simulate_key_press(*(p_note + i), *(p_sleep_time + i));
  }
  Sleep(sleep_pause);
}

void start(){
  int amount_notes = 0;
  amount_notes = 17;
  int sleep_time_prelude[] = {1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000};
  int notes_prelude[] = {1,2,1,3,1,1,5,1,1,1,6,1,1,1,1,10,1};
  play_part(sleep_time_prelude, notes_prelude, amount_notes, 1000);
}

int main(){
    Sleep(5000);
    ip.type = INPUT_KEYBOARD;
    ip.ki.wScan = 0;
    ip.ki.time = 0;
    ip.ki.dwExtraInfo = 0;

    start();

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...