为什么在Windows Cmd 工程里使用SetWindowsHookEx就不起作用?
为什么在Windows Cmd 工程里使用SetWindowsHookEx就不起作用?
而当我用mfc的dialog里,这些函数都有用?
// DateKey.cpp : Defines the entry point for the console application.
//
#include <windows.h>
#include "stdafx.h"
#include "DateKey.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;
//Global data
static HHOOK g_hKeyboardHook = NULL;
static LPCTSTR g_pTimeFormat = _T("%Y-%m-%d");
//Function declaration
LRESULT CALLBACK KeyboardHookProc(
int nCode, // hook code
WPARAM wParam, // message identifier
LPARAM lParam // message data
)
{
static bool needBlock = false;
if (nCode < 0) {
return(CallNextHookEx(g_hKeyboardHook,nCode,wParam,lParam));
}
if (((GetKeyState(VK_F6) & 128) > 0) && (false == needBlock)) {
needBlock = true;
CString s = CTime::GetCurrentTime().Format(g_pTimeFormat);
for(int i = 0; i < s.GetLength(); ++i) {
BYTE vkCode = (BYTE)VkKeyScan(s.GetAt(i));
TRACE("vkCode=%x\n", vkCode);
keybd_event(vkCode, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
keybd_event(vkCode, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
TRACE("win+t:%s\n", (LPCTSTR )s);
needBlock = false;
}
return(CallNextHookEx(g_hKeyboardHook,nCode,wParam,lParam));
}
bool InstallKeyboardHook(HINSTANCE hinstance)
{
if (NULL != g_hKeyboardHook) {
return false;
}
g_hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProc, hinstance, 0);
if (NULL == g_hKeyboardHook) {
//DWORD error = GetLastError();
AfxMessageBox(_T("Sorry, can't hook for DateKey"));
return false;
}
else {
return true;
}
}
bool RemoveKeyboardHook()
{
if (NULL == g_hKeyboardHook) {
return true;
}
if (TRUE == UnhookWindowsHookEx(g_hKeyboardHook)) {
g_hKeyboardHook = NULL;
return true;
}
else {
AfxMessageBox(_T("Sorry, can't unhook for DateKey"));
return false;
}
}
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
{
if (argc > 1) {
g_pTimeFormat = argv[1];
}
InstallKeyboardHook(::GetModuleHandle(NULL));
}
while(1) {
;
}
RemoveKeyboardHook();
return nRetCode;
}