之前做了一个游戏的辅助程序,其中要利用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字母数字啥的也没反应,
是不是我的写法有问题呢?

解决方案 »

  1.   

    参考:(看下面的评论)http://blog.csdn.net/zswang/archive/2007/03/28/1543956.aspx
      

  2.   

    另外SendKeys.SendWait("{BS}"); //空格 
      

  3.   

    SendKeys.Send("{BREAK}");
     VK_SPACE = 0x20,
    屏幕键盘
      

  4.   

    这个之前我也研究过 因为键盘没有休眠键,想自己做一个出来试了很多种办法 可惜最终没成功,当时看的资料,最好的解决方法是用c++写一个拦截程序,然后直接在底层发送自己的空格的按键码,这样可以欺骗过绝大多数系统层的程序,你可以用c++写一个 然后做成dll 让c#来调用(小弟不太会用c# 只会c++和basic 反正vb下能这么做),贴个你个别人写的c++的拦截程序
    #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;
    }