我编写了在窗口不在焦点时检测按键的代码:
// MainHamsterDlg.cpp : implementation file
#include "stdafx.h"
#include "MainHamsterDlg.h"
// MainHamsterDlg dialog
IMPLEMENT_DYNAMIC(MainHamsterDlg, CDialogEx)
MainHamsterDlg::MainHamsterDlg(CWnd* pParent)
: CDialogEx(MainHamsterDlg::IDD, pParent)
{}
void MainHamsterDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(MainHamsterDlg, CDialogEx)
ON_WM_TIMER()
END_MESSAGE_MAP()
HHOOK _hook;
KBDLLHOOKSTRUCT kbdStruct;
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode >= 0)
{
if (wParam == WM_KEYUP)
{
kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
if (kbdStruct.vkCode == VK_INSERT)
{
//I want start timer there
}
}
}
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
void SetHook()
{
if (!(_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0)))
{
MessageBox(NULL, "Failed to install hook!", "Error", MB_ICONERROR);
}
}
void ReleaseHook()
{
UnhookWindowsHookEx(_hook);
}
BOOL MainHamsterDlg::OnInitDialog()
{
SetHook();
//SetTimer(0, 0, NULL); <<<------- this starts timer
CDialogEx::OnInitDialog();
return TRUE;
}
void MainHamsterDlg::OnTimer(UINT nIDEvent)
{
//do something
CDialog::OnTimer(nIDEvent);
}
当窗口没有聚焦时,我想在按键时启动计时器。我是否需要使用一些指针或从该函数调用 SetTimer 的内容。如果在应用程序没有焦点时让计时器在按键上工作有更好的问题,我想知道。