之前做了一个游戏的辅助程序,其中要利用Windows API 的 keybd_event 函数来模拟键盘按下和弹起空格键。
后来这个游戏不知道用啥办法,使keybd_event模拟按下和弹起空格键不起作用了,但模拟其他按键还管用。
之后发帖,先有朋友告诉用SendKeys,但sendkeys好像不太容易发送空格键,而且要分别实现按下和弹起的功能,SendKeys好像不支持
再有朋友告诉用SendMessage实现,我这样写(打开一个记事本做实验):
//wMsg参数常量值:
//WM_KEYDOWN 按下一个键
public static int WM_KEYDOWN = 0x0100;
//释放一个键
public static int WM_KEYUP = 0x0101;
//按下某键,并已发出WM_KEYDOWN, WM_KEYUP消息
public static int WM_CHAR = 0x102; public const int VK_SPACE = 0x20; [DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);System.Diagnostics.Process[] GamesProcess = System.Diagnostics.Process.GetProcessesByName("notepad");
if (GamesProcess.Length == 0) return;
IntPtr hWnd = GamesProcess[0].Handle; SendMessage(hWnd, WM_KEYDOWN, VK_SPACE, 0);
SendMessage(hWnd, WM_KEYUP, VK_SPACE, 0); 可以得到记事本的句柄hWnd,但SendMessage空格后,记事本里也没啥变化,SendMessage字母数字啥的也没反应,
是不是我的写法有问题呢?
后来这个游戏不知道用啥办法,使keybd_event模拟按下和弹起空格键不起作用了,但模拟其他按键还管用。
之后发帖,先有朋友告诉用SendKeys,但sendkeys好像不太容易发送空格键,而且要分别实现按下和弹起的功能,SendKeys好像不支持
再有朋友告诉用SendMessage实现,我这样写(打开一个记事本做实验):
//wMsg参数常量值:
//WM_KEYDOWN 按下一个键
public static int WM_KEYDOWN = 0x0100;
//释放一个键
public static int WM_KEYUP = 0x0101;
//按下某键,并已发出WM_KEYDOWN, WM_KEYUP消息
public static int WM_CHAR = 0x102; public const int VK_SPACE = 0x20; [DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);System.Diagnostics.Process[] GamesProcess = System.Diagnostics.Process.GetProcessesByName("notepad");
if (GamesProcess.Length == 0) return;
IntPtr hWnd = GamesProcess[0].Handle; SendMessage(hWnd, WM_KEYDOWN, VK_SPACE, 0);
SendMessage(hWnd, WM_KEYUP, VK_SPACE, 0); 可以得到记事本的句柄hWnd,但SendMessage空格后,记事本里也没啥变化,SendMessage字母数字啥的也没反应,
是不是我的写法有问题呢?
VK_SPACE = 0x20,
屏幕键盘
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <term.h>
#include <curses.h>
#include <unistd.h>
static struct termios initial_settings, new_settings;
static int peek_character = -1;
void init_keyboard();
void close_keyboard();
int kbhit();
int readch();
int main()
{
int ch = 0;
init_keyboard();
while(ch != ‘q’) {
printf(“looping\n”);
sleep(1);
if(kbhit()) {
ch = readch();
printf(“you hit %c\n”,ch);
}
}
close_keyboard();
exit(0);
}
void init_keyboard()
{
tcgetattr(0,&initial_settings);
new_settings = initial_settings;
new_settings.c_lflag &= ~ICANON;
new_settings.c_lflag &= ~ECHO;
new_settings.c_lflag &= ~ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}
void close_keyboard()
{
tcsetattr(0, TCSANOW, &initial_settings);
}
int kbhit()
{
char ch;
int nread;
if(peek_character != -1)
return 1;
new_settings.c_cc[VMIN]=0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0,&ch,1);
new_settings.c_cc[VMIN]=1;
tcsetattr(0, TCSANOW, &new_settings);
if(nread == 1) {
peek_character = ch;
return 1;
}
return 0;
}
int readch()
{
char ch;
if(peek_character != -1) {
ch = peek_character;
peek_character = -1;
return ch;
}
read(0,&ch,1);
return ch;
}