如何利用windows API 模擬鍵盤按鍵

 
以前為了給工廠測試程式,常會在韌體內寫一些後門去搭配測試程式
譬如說如果要模擬keyboard LED的亮滅,就會在韌體內寫一個開關LED的後門

結果後來看MSDN,知道windows就有API可以去模擬鍵盤了,就甘心
今天我們要用的是
 
VOID keybd_event(      
    BYTE bVk,
    BYTE bScan,
    DWORD dwFlags,
    PTR dwExtraInfo
);
 
以下是我模擬Num/Caps/Scrol Lock 的程式
執行後,LED會亮滅,而系統也會根據Numlock key等會有相對應的行為
 
#include "stdafx.h"
#include "test.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;
void KbdLEDControl(BYTE );

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
 int nRetCode = 0;

 // initialize MFC and print and error on failure
 if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
 {
  // TODO: change error code to suit your needs
  cerr << _T("Fatal Error: MFC initialization failed") << endl;
  nRetCode = 1;
 }
 else
 {
  // TODO: code your application's behavior here.
// if (GetKeyState(VK_NUMLOCK)&0x01){  // 偵測key的狀態,這裡用不到
BYTE KeyTBL[]={VK_NUMLOCK,VK_CAPITAL,VK_SCROLL};   // key的message ID

  int i=0;

  for (i=0;i<=2;i++)
  {
    KbdLEDControl (KeyTBL[i]);
    Sleep(1000);
    KbdLEDControl (KeyTBL[i]);
  }
 }
 return nRetCode;
}

void KbdLEDControl (BYTE KeyID){
// 模擬按下鍵盤,但尚未放開
  keybd_event( KeyID,
       0x45,
                      KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                      0);
// 模擬放開按鍵
 
keybd_event( KeyID,
                      0x45,
                      KEYEVENTF_EXTENDEDKEY | 0,
                      0 );
}
 
http://revolution-30.blogspot.tw/search/label/win32
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 cj6m3 的頭像
    cj6m3

    勇ㄅㄟㄅㄟ胡言亂語堂

    cj6m3 發表在 痞客邦 留言(0) 人氣()