How to check mouse is not moved from last 5 seconds? - c++

I'm working on a task for my game program, in which I want to hide my mouse after 10 seconds from my screen. However I'm able to check the mouse move condition...
Here is my code..
using namespace std;
HHOOK g_hMouseHook;
LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode >= 0)
{
PMSLLHOOKSTRUCT pmll = (PMSLLHOOKSTRUCT) lParam;
switch (wParam)
{
case WM_MOUSEMOVE:
printf("Mouse has been moved\n");
break;
}
}
return CallNextHookEx(g_hMouseHook, nCode, wParam, lParam);
}
int _tmain(int argc, _TCHAR* argv[])
{
MSG msg;
g_hMouseHook = SetWindowsHookEx( WH_MOUSE_LL, LowLevelMouseProc, GetModuleHandle(NULL), 0 );
if (!g_hMouseHook)
printf("err: %d\n", GetLastError());
while ( GetMessage(&msg, NULL, 0, 0) )
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(g_hMouseHook);
return (int) msg.wParam;
}
I'm doing it by using hook and it is displaying the mouse movement successfully.
Now I'm searching for an option with which I can also check that my mouse has not been moved.
*one thing I'm making it on console.
I've changed the mouse cursor or the hide by using LoadCursorfromFile and it's working properly.
Please share your opinions on to check when the mouse is not moving.

Call TrackMouseEvent to set up an idle time of 5000 milliseconds. You'll get a WM_HOVER message after 5 seconds. You could reset the timer on every keypress, but that's a bit inefficient. Instead, on every keypress you should update a lastKeyPressedTime variable. Now, if WM_HOVER arrives after 5 seconds, you check to see if the last keypress is 5 seconds ago. If it is, you have neither keyboard nor mouse input an can remove the mouse.
If you had keyboard input in the last 5 seconds while the mouse was idle, you should reset the TrackMouseEvent. If you're lazy, reset it to 5 seconds again. If you're being accurate, you have to get a bit more creative.

Perhaps GetLastInputInfo is what you need MSDN here.
For example, to get the elapsed milliseconds since the last mouse move or key press, you might have a function like this:
DWORD GetIdleTime()
{
LASTINPUTINFO pInput;
pInput.cbSize = sizeof(LASTINPUTINFO);
if (!GetLastInputInfo(&pInput))
{
// report error, etc.
}
// return idle time in millisecs
return pInput.dwTime;
}

Related

What information does dwExtraInfo hold for the PMOUSEHOOKSTRUCT?

LRESULT CALLBACK LowLevelMouseProc(_In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
BOOL fpassmove = FALSE;
if (nCode == HC_ACTION)
{
switch (wParam)
{
case WM_MOUSEMOVE: // how do i catch a dx instead of a cursor points?
PMOUSEHOOKSTRUCT me = (PMOUSEHOOKSTRUCT)lParam;
printf("x:%d\ny:%d\nextrainfo:%04X\n", me->pt.x,me->pt.y, me->dwExtraInfo );
break;
}
}
return(fpassmove ? 1 : CallNextHookEx(NULL, nCode, wParam, lParam));
}
int main()
{
// Install the low-level keyboard & mouse hooks
HHOOK hhkLowLevelMouse = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, 0, 0);
// Keep this app running until we're told to stop
MSG msg;
while (!GetMessage(&msg, NULL, NULL, NULL)) { //this while loop keeps the hook
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hhkLowLevelMouse);
return(0);
}
I am looking at all mouse moment from a global hook, and I'm trying to find the dx and dy of the mouse event, And I was hoping to find it in "dwExtraInfo". However, I have no idea how to make sense of the data inside "dwExtraInfo".
the windows documentation is not helpful in telling me what the data in dwExtraInfo means
dwExtraInfo
Type: ULONG_PTR
Additional information associated with the message.
Could not find any documentation on dwExtraInfo directly, but found something related: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessageextrainfo:
Return value
Type: LPARAM
The return value specifies the extra information. The meaning of the
extra information is device specific.
One example of such device specific extra information is Pen gestures: https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages
Distinguishing Pen Input from Mouse and Touch
When your application receives a mouse message (such as
WM_LBUTTONDOWN), it may call the GetMessageExtraInfo function to
evaluate whether the message originated from a pen or a mouse device.
The value returned from GetMessageExtraInfo needs to be mask-checked
against 0xFFFFFF00, and then compared with 0xFF515700. The following
definitions may make this clearer:
#define MI_WP_SIGNATURE 0xFF515700
#define SIGNATURE_MASK 0xFFFFFF00
#define IsPenEvent(dw) (((dw) & SIGNATURE_MASK) == MI_WP_SIGNATURE
If the comparison is true, then this mouse message was generated by a
Tablet PC pen or touch screen. In all other cases, you can assume that
this message was generated by a mouse device.
The lower 8 bits returned from GetMessageExtraInfo are variable. Of
those bits, 7 (the lower 7, masked by 0x7F) are used to represent the
cursor ID, zero for the mouse or a variable value for the pen ID.
Additionally, in Windows Vista, the eighth bit, masked by 0x80, is
used to differentiate touch input from pen input (0 = pen, 1 = touch).

C++ Animating a button with MoveWindow()

I am new to C++ and seem to be stuck. I basically have a Window and a Button inside it(also created with CreateWindow()). I want to have the button moving on the X axis, I tried doing with MoveWindow() but I cant seem to do the animation effect. I tried writing it in a for loop but I have not found what to use to delay the animation. I would appreciate any help.
for (int i = 0; i < 50; i++) {
MoveWindow(g_MovingDot, i, ButtonTop, ButtonWidth, ButtonHeight, true);
//Delay it somehow
}
Would this be the right way to do it? I just want the button to move slowly to the right.
Use the SetTimer function to be notified when the time-out value is elapse.
Implement a function with the signature
VOID (CALLBACK* TIMERPROC)(HWND, UINT, UINT_PTR, DWORD);
and pass a function pointer to SetTimer, to register a callback procedure .
Use a global control variable, which controls the animation of the window. In the following code snippet the control variable is named i_g.
When the timer is elapsed, then the callback procedure is called. Increment the control variable, slightly move the dialog element and restart the timer, until the final position is reached.
The animation time is controlled by the number of animation steps and the time interval of a single step.
int g_i=0;
void CALLBACK BtnTimer( HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime )
{
KillTimer( hwnd, idEvent );
if ( g_i < 50 )
{
MoveWindow(g_MovingDot, i, ButtonTop, ButtonWidth, ButtonHeight, true);
g_i ++;
SetTimer( hwnd, idEvent, 100 /* time milliseconds */, &BtnTimer );
}
}
void AnimateButton( HWND hDialogWnd //* HWND from Dialog */)
{
g_i = 0;
SetTimer( hDialogWnd, 0 /* idEvent */, 100 /* time milliseconds */, &BtnTimer );
}

Windows Journal playback hook (WH_JOURNALPLAYBACK) ignores EVENTMSG HWND parameter

I am working a program to simulate keyboard and mouse clicks programmatically. It need to send the clicks to a target window handle (ex: notepad edit control). I am getting the handle of notepad window and generating generating WM_KEYDOWN, WM_SYSKEYDOWN, WM_KEYUP, WM_SYSKEYUP messages for that window. The events are stored in queue, and later on played using a WH_JOURNALPLAYBACK hook.
For the code snippet below, the target hwnd in the playback proc though set correctly, messages never reach to the target handle. If I bring the notepad to foreground, it does receive the messages.
I am not sure why WH_JOURNALPLAYBACK ignores the handle parameter. I would have liked to generate a series of automation messages for various handles and played it back so that even without bringing the window into focus we can send keyboard and mouse events.
Please let me know
if messages to various target handles can be sent using a journal
playback hook
why in code below hwnd is ignored
..
#include <queue>
#include <iostream>
#include <windows.h>
using std::cout;
using std::endl;
using std::error;
struct Event
{
UINT msg;
UINT wparam;
UINT lparam;
HWND hwnd;
Event(UINT m, UINT wp, UINT lp, HWND h)
:msg(m),
wparam(wp),
lparam(lp),
hwnd(h)
{}
};
HHOOK jhook= NULL;
std::queue<Event> events;
bool gotoNextMsg = false;
LRESULT CALLBACK JournalPlaybackProc(int code, WPARAM wParam, LPARAM lParam)
{
switch( code )
{
case HC_SKIP:
cout<<"skip: "<<endl;
if(!events.empty())
{
events.pop();
}
break;
case HC_GETNEXT:
{
cout<<"next: "<<events.size()<<endl;
gotoNextMsg = true;
EVENTMSG * evm = (EVENTMSG*) lParam;
Event e = events.front();
switch(e.msg)
{
case WM_KEYDOWN:
cout<<"WM_KEYDOWN"<<endl;
break;
case WM_KEYUP:
cout<<"WM_KEYUP"<<endl;
break;
case WM_SYSKEYDOWN:
cout<<"WM_SYSKEYDOWN"<<endl;
break;
case WM_SYSKEYUP:
cout<<"WM_SYSKEYUP"<<endl;
break;
}
cout<<"handle: "<<e.hwnd<<endl;
cout<<"handle1:"<<evm->hwnd<<endl;
evm->message = e.msg;
evm->paramL = e.wparam;
evm->paramH = e.lparam;
evm->hwnd = e.hwnd;
evm->time = ::GetTickCount();
}
break;
default:
if( code < 0 )
::CallNextHookEx(jhook, code, wParam, lParam);
break;
}
if(events.empty())
{
cout<<"uinstalled"<<endl;
::UnhookWindowsHookEx(jhook);
::PostMessage(NULL, WM_USER+100, 0, 0);
}
return 0;
}
A journal hook injects events into the system message queue. For keyboard and mouse messages, the system dispatches them to the current focused window, same as if the user had input them manually. The HWND you specify in the event is not used, it gets replaced during dispatching.
And if you consider that a recorded journal can be played multiple times, and its data can persist across application instances and even reboots, and that HWNDs can be reused for different things over time, it should make sense why a journal playback cannot make use of an event's HWND even if the system message queue were not involved.
So, you cannot use WH_JOURNALPLAYBACK to target a specific window that is not in the foreground. You would have to send the recorded messages yourself. But be aware of some caveats that Raymond Chen has blogged about:
You can't simulate keyboard input with PostMessage
Simulating input via WM_CHAR messages may fake out the recipient but it won't fake out the input system

Global keyboard hook with WH_KEYBOARD_LL and keybd_event (windows)

I am trying to write a simple global keyboard hook program to redirect some keys. For example, when the program is executed, I press 'a' on the keyboard, the program can disable it and simulate a 'b' click. I do not need a graphic ui, just a console is enough (keep it running)
My plan is to use global hook to catch the key input, and then use keybd_event to simulate the keyboard. But I have some problems.
The first problem is that the program can correctly block 'A' but if I hit 'A' on the keyboard once, the printf in the callback function is executed twice, as well as the keybd_event. So if i open a txt file, i click 'A' once, there are two 'B's input. why is that?
The second question is that why the hook using of WH_KEYBOARD_LL can work on other process without a dll? I thought that we had to use a dll to make a global hook until I wrote this example...
#include "stdafx.h"
#include <Windows.h>
#define _WIN32_WINNT 0x050
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
BOOL fEatKeystroke = FALSE;
if (nCode == HC_ACTION)
{
switch (wParam)
{
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
if (fEatKeystroke = (p->vkCode == 0x41)) { //redirect a to b
printf("Hello a\n");
keybd_event('B', 0, 0, 0);
keybd_event('B', 0, KEYEVENTF_KEYUP, 0);
break;
}
break;
}
}
return(fEatKeystroke ? 1 : CallNextHookEx(NULL, nCode, wParam, lParam));
}
int main()
{
// Install the low-level keyboard & mouse hooks
HHOOK hhkLowLevelKybd = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, 0, 0);
// Keep this app running until we're told to stop
MSG msg;
while (!GetMessage(&msg, NULL, NULL, NULL)) { //this while loop keeps the hook
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hhkLowLevelKybd);
return(0);
}
Many thanks!
Your callback function execute twice because of WM_KEYDOWN and WM_KEYUP.
When you down a key of your keyboard, windows calls the callback function with WM_KEYDOWN message and when you release the key, windows calls the callback function with WM_KEYUP message. That's why your callback function execute twice.
You should change your switch statement to this:
switch (wParam)
{
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
if (fEatKeystroke = (p->vkCode == 0x41)) //redirect a to b
{
printf("Hello a\n");
if ( (wParam == WM_KEYDOWN) || (wParam == WM_SYSKEYDOWN) ) // Keydown
{
keybd_event('B', 0, 0, 0);
}
else if ( (wParam == WM_KEYUP) || (wParam == WM_SYSKEYUP) ) // Keyup
{
keybd_event('B', 0, KEYEVENTF_KEYUP, 0);
}
break;
}
break;
}
About your second question, I think you have already got from #Ivan Danilov answer.
First one is easy. You get one for key down and another for key up. :)
As for the why it can work without a DLL - that's because it is a global hook. Unlike thread-specific ones it is executed in your own process, not in the process where keyboard event happened. It is done via message sending to the thread which has installed the hook - that's precisely why you need message loop here. Without it your hook can't be ran as there would be no one to listen for incoming messages.
The DLL is required for thread-specific hooks because they're called in the context of another process. For this to work, your DLL should be injected into that process. It is just not the case here.
I have run your code but nothing happend? What wrong with me?
Base on msdn that WH_KEYBOARD_LL message is "Global only" It mean more than that.
The system calls this function .every time a new keyboard input event is about to be posted into a thread input queue.
This message is special case. You also need an DLL to make a real global hook for other message.

Key input lags when using Windows API and WM_KEYDOWN C++

So I'm trying to make a program using Windows API (and DirectX9, if it matters) and am trying to use WM_KEYDOWN and WM_KEYUP to get input from the keyboard. This is the related part of my code right now. The idea is that the "keyTimes" array should store the number of frames that a key has been held down.
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
Game* Game::s_instance = NULL;
LPDIRECT3D9 d3dObject;
LPDIRECT3DDEVICE9 d3dDevice;
Game::Game(){
for(int i=0; i<256; i++){
keyTimes[i]=0;
}
}
//....
Game* Game::Instance(){
if(Game::s_instance==NULL){
s_instance = new Game();
}
return s_instance;
}
//Checks to see if key was pressed, and adds to value
void Game::keyCheck(int keyNum, bool pressed){
if(pressed){
keyTimes[keyNum]++;
}
else{
keyTimes[keyNum]=0;
}
}
//Returns time that key has been pressed
int Game::keyPressed(int keyNum){
return keyTimes[keyNum];
}
//Returns true if key was hit once, and doesn't return true again until the key is let go and hit again.
bool Game::keyHit(int keyNum){
return keyTimes[keyNum]==1;
}
//Returns true only if the key has been held for delay
bool Game::keyHeld(int keyNum, int delay){
if(delay==0)
delay=1;
return keyTimes[keyNum]==delay;
}
//Returns true everyXFrame frames.
bool Game::keyPressedDelay(int keyNum, int everyXFrame){
if(everyXFrame<2){
return false;
}
return keyTimes[keyNum]%everyXFrame==1;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_KEYDOWN:
{
Game::Instance()->keyCheck(wParam,true);
return 0;
}
break;
case WM_KEYUP:
{
Game::Instance()->keyCheck(wParam,false);
return 0;
}
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
//........
//Inside the main function while loop....
if(Game::Instance()->keyHit(VK_LEFT)){
thing->move(-3,0);
}
if(Game::Instance()->keyHit(VK_RIGHT)){
thing->move(3,0);
}
if(Game::Instance()->keyHit(VK_UP)){
thing->move(0,-3);
}
if(Game::Instance()->keyHit(VK_DOWN)){
thing->move(0,3);
}
//.......
So when I try using the "KeyPressed" function as the boolean to move "thing" in the main function, it moves three pixels, stops for about half a second, and then starts moving again. It will also stop again if I try to hit another key while holding the first down. When I use "KeyHit" to move it, it goes about 9-12 pixels, then stops (rather than going only 3).
How would I change my code so that the functions work as commented, without any lag?
EDIT 3/26/12: I have managed to fix the code. It turns out that the problem was simply that I was using the GetMessage function in my main loop, which waits for input before moving, where I should have been using PeekMessage.
keyHit works only for the first 500 milliseconds because autorepeat kicks in and causes the hit count to go above 1.
Add some debug tracing to observe what messages you're receiving and what the value of keyTimes is each time you check it in your main game loop. That will probably identify the problem.
So when I try using the "KeyPressed" function as the boolean to move "thing" in the main function, it moves three pixels, stops for about half a second, and then starts moving again.
This is standard windows behaviour.
For example if you go to the Windows Control Panel and in the Keyboard properties set the Repeat Delay to short you will find that your delay times are now reduced.