我编写的代码可以在窗口未对焦时检测按键:
// 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的内容。如果有一个更好的问题,当应用程序没有聚焦时,按键按下时,我想知道。