The best answer what i get is on this web page writen by Andy
SetTimer from non-static function
-
31-05-2022 - |
Question
I write code that detects key press when window not in focus:
// 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);
}
I want start timer on key press when window not focused. Do I need use some pointers or what to call SetTimer from that function. If there is a better issue to make timer work on key press when application has no focused I wish to know.
Solution 2
OTHER TIPS
The documentation of the SetTimer (MSDN) says that you need to pass an HWND so that you get a OnTimer notification. So, you will have to somehow get the CDialo->m_hWnd to the global win32 SetTimer function.
Other option would be to invoke a member function of MainHamsterDlg from the window hook function on key-press and the dialog can call its on SetTimer (CWnd::SetTimer). Still HookCallback needs to know about the dialog object reference somehow.
I'm not aware of any other method to get the key-board message to a non-focussed window.