global low level keyboard hook being called when SendInput is made. how to prevent it? - c++

I have a win 32 application written in c++ which sets the low level keyboard hook. now i want to sendInput to any app like word / notepad. how do i do this?
i have already done enough of using findwindow / sendmessage. for all these, i need to know edit controls. finding the edit control is very difficult.
since SendInput works for any windows application, i want to use it. the problem is i get a call to my callback function with the pressed key.
for e.g i pressed A and i want to send U+0BAF unicode character to the active applciation windows. in this case, assume it is notepad.
the problem is i get two characters U+0BAF and A in the notepad.
A is being sent because i am calling CallNextHookEx( NULL, nCode, wParam, lParam);
if i return 1 after sendInput, then nothing is sent to notepad.
any suggestion?

If I understood your problem correctly, you should ignore "injected" key events in your hook procedure, like this:
LRESULT CALLBACK
hook_proc( int code, WPARAM wParam, LPARAM lParam )
{
KBDLLHOOKSTRUCT* kbd = (KBDLLHOOKSTRUCT*)lParam;
// Ignore injected events
if (code < 0 || (kbd->flags & LLKHF_INJECTED)) {
return CallNextHookEx(kbdhook, code, wParam, lParam);
}
...
Update: additionally, you have to eat characters and notify some other routine for a character press through Windows messages.
Example:
...
// Pseudocode
if (kbd->vkCode is character) {
if (WM_KEYDOWN == wParam) {
PostMessage(mainwnd, WM_MY_KEYDOWN, kbd->vkCode, 0);
return 1; // eat the char, ie 'a'
}
}
return CallNextHookEx(kbdhook, code, wParam, lParam);
And, in some other module, you handle WM_MY_KEYDOWN:
ie, #define WM_MY_KEYDOWN (WM_USER + 1)
and call the appropriate routine that will generate new key events.

Related

Global Mouse Hook: Modify mouse position before input hits hooked application

I created a global mouse hook where I tried to change the x and y cursor position that the hooked application receives without actually moving the cursor. For some reason it did not work. So I tried to change the cursor position to see if it would change anything. But that didn't work either; the input reached the window before the cursor moved. Below is my code.
LRESULT CALLBACK procMouseMsg(int nCode, WPARAM wParam, LPARAM lParam){
//this is the hook procedure
if (wParam == WM_LBUTTONDOWN){
// Tactic #1 -problem: Nothing seems to happen...?
((PMSLLHOOKSTRUCT)lParam)->pt.x = 389; //
((PMSLLHOOKSTRUCT)lParam)->pt.y = 15;
// Tactic #2 -problem: cursor moves after input hits hooked application
SetPhysicalCursorPos(389, 15);
// Tactics were not used at the same time.
}
return CallNextHookEx(hkKey, nCode, wParam, lParam);
}
void __stdcall SetHook()
{
if (hkMouse == NULL){
hkMouse = SetWindowsHookEx(WH_MOUSE_LL, procMouseMsg, hInstHookDll, 0);
}
}
Am I missing something big here? Maybe I should just kill the input in CallNextHookEx and then move the cursor, manually send an input and then move the cursor back? I feel like this should be easier.
BTW I'm not writing a keylogger or anything sketchy. I'm trying to do an operating system overlay. It seems like people assume the worst.

How to make Windows Hot Keys work in Direct X environments?

I am programming a really simple MFC C++ Application which is working with HotKeys. To set a HotKey I use the following method from the WinAPI for my application:
BOOL RegisterHotKey(
HWND hWnd, // window to receive hot-key notification
int id, // identifier of hot key
UINT fsModifiers, // key-modifier flags
UINT vk // virtual-key code
);
To catch any HotKey Message I use: ON_MESSAGE(WM_HOTKEY,OnHotKey) in the message map and this Callback Method to test it's functionality:
LRESULT OnHotKey(WPARAM wParam, LPARAM lParam)
{
if (wParam == MY_HOTKEY_KEY_CODE)
{
MessageBox(L"HotKey was pressed!");
return TRUE;
}
return FALSE;
}
When a HotKey is pressed it enters the OnHotKey Method and does not process the key normally. For example if I write some text in Notepad and press "O" as HotKey, the "O" wont append to my text but the Message "HotKey was pressed!" appears, which is nice.
But when I am in any Direct X Game and press my HotKey, it is not sent to my application. Also when typing something in a Direct X environment the HotKey just works as normal key.
Is Direct X binding all key inputs somehow? Is there a way to make Windows HotKeys work with Direct X environments?

C++: Trying to hook a message box and change its position

I recently started coding in C++ and I am very new to it. (I code in Javascript, PHP, Java and Obj-C more often)
I'm practicing how to hook a message box and change its position. This is what I have in my .cpp file (after reading this SO post).
#include <iostream>
#pragma comment(lib,"User32.lib")
#include <windows.h>
HHOOK hhookCBTProc = 0;
LRESULT CALLBACK pfnCBTMsgBoxHook(int nCode, WPARAM wParam, LPARAM lParam){
if (nCode == HCBT_CREATEWND)
{
CREATESTRUCT *pcs = ((CBT_CREATEWND *)lParam)->lpcs;
if ((pcs->style & WS_DLGFRAME) || (pcs->style & WS_POPUP))
{
HWND hwnd = (HWND)wParam;
SetWindowPos(hwnd, HWND_TOP,130,122, 0, 0,SWP_NOSIZE);
}
}
return (CallNextHookEx(hhookCBTProc, nCode, wParam, lParam));
}
int main(void)
{
hhookCBTProc = SetWindowsHookEx(WH_CBT,pfnCBTMsgBoxHook,
0, GetCurrentThreadId());
int sResult = MessageBox ( NULL, "Hooked!", "oh my", MB_OK );
UnhookWindowsHookEx(hhookCBTProc);
return 0;
}
For some reason the position of the message box isn't changing. Where did it go wrong?
(I know I can create a customized window or dialog. But I am doing it this way because I want to learn how to hook a message box and where I did wrong.)
Firstly you should check in the debugger that your hook is actually being called, if you haven't already.
Secondly, at the time the HCBT_CREATEWND hook event is triggered, the window has only just been created - the system has yet to size and position it. It will do this with the values in the CREATESTRUCT after the hook returns - overriding your SetWindowPos call.
See the docs from MSDN on the lParam value for this particular hook event:
Specifies a long pointer to a CBT_CREATEWND structure containing
initialization parameters for the window. The parameters include the
coordinates and dimensions of the window. By changing these
parameters, a CBTProc hook procedure can set the initial size and
position of the window.
Therefore, the correct way to use this hook to change a window's position is to modify the values in the CREATESTRUCT directly.
Also note that it's quite possible that the dialog manager sizes and positions the window after creation, so if you find that this still isn't working for you, you may need to try watching for the HCBT_MOVESIZE event instead.
From the docs
At the time of the HCBT_CREATEWND notification, the window has been
created, but its final size and position may not have been determined
and its parent window may not have been established.
Maybe try hooking into CBT_ACTIVATE instead.

get mouse coordinates when user press Ctrl and click

I want to get mouse click coordinates X and Y when user press Ctrl and click at same time.
User may click anywhere on the screen or programs. I want my program to catch the event and get coordinates when Ctrl key is down pressed and mouse click occurs at same time. I want to get system coordinates X and Y, not the window coordinates of other programs.
I'm using C++ .
How to do that ?
Windows OS, WIN API code
I'm doing next which is not working:
HHOOK MouseHook;
LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam){
PKBDLLHOOKSTRUCT k = (PKBDLLHOOKSTRUCT)(lParam);
POINT p;
if(wParam == WM_RBUTTONDOWN)
{
// right button clicked
GetCursorPos(&p);
//p.x
//p.y
//my program is never getting here, why ?
}
}
MouseHook = SetWindowsHookEx(WH_MOUSE_LL,(HOOKPROC)MouseHookProc,0,0);
if I change the above line to: MouseHook = SetWindowsHookEx(WH_MOUSE,(HOOKPROC)MouseHookProc,GetModuleHandle(NULL),0);
then it will work only for my own program window, but not hooking clicks outside of my program
Have you read this article? link
First of all, if you want to catch system entire mouse + keyboard event, your hooking function must be placed on a dll.
1)If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
Like below,
if(nCode < 0)
{
CallNextHookEx(hook, nCode, wParam, lParam);
return 0;
}
If CallNextHookEx is not called, there is a chance that other processes that have installed hook may not get the events correctly.
2)And then, check nCode again, whether it is HC_ACTION.
switch (nCode)
{
case HC_ACTION:
...
3)Finally, you can check WPARAM for WM_RBUTTONDOWN, and LPARAM for MSLLHOOKSTRUCT
The way I would approach is I would create a global variable say
int ctrl_pressed = 0
/*
0 -- ctrl nt pressed
1 -- Crtl Pressed
*/
Step 1: Now I would handle both WM_KEYDOWN and WM_KEYUP for ctrl
Step 2: In the callback of WM_KEYDOWN (if lparam is ctrl ) I would set ctrl_pressed to 1.
And in case of WM_KEYUP I would set ctrl_pressed to 0.
Step 3: Now Finally ill handle WM_MOUSECLICKED
and then check if ctrl_pressed(global) is 1 , which if true I can just get the coordinates.
This is just an approach may be not the most efficient solution.
Wait for more experienced WIN32 Developers to give their input on this.

C++ Console app, SetWindowsHookEx, Callback is never called

I have a little console application that has an embedded v8 engine, and I would like to add a hook to register key events. This all worked before when I was using Qt and QtScript, but I am porting it all over to straight C++ in VC++ 2008. The application compiles and runs, but the hook is never called, here is the relevant code:
In main()
HWND hwndC = GetConsoleWindow() ;
HINSTANCE hInst = (HINSTANCE)GetWindowLong( hwndC, GWL_HINSTANCE );
if (SetWindowsHookEx(WH_KEYBOARD_LL, HookProc, hInst, NULL) == 0) {
printf("Failed to set hook\n");
} else {
printf("Hook established\n");
}
g->RunScript(argc,argv);
And the proc:
LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
printf("HookProc called\n");
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT) (lParam);
if (wParam == WM_KEYDOWN) {
keyDown(p,g);
} else if (wParam == WM_KEYUP) {
keyUp(p,g);
}
fflush(stdout);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
This is essentially an expansion on shell.cc from the v8 sample code. I wonder if it is somehow blocking? I admit to not really knowing what I am doing here, just playing around and learning but this one has me stumped.
Inside of keyDown say, I have something like this:
v8::Handle<v8::String> callback_name = v8::String::New("onKeyDown");
v8::Handle<v8::Value> callback_val = g->_context->Global()->Get(callback_name);
if (!callback_val->IsFunction()) {
printf("No onKeyDown handler found\n");
return;
}
v8::Handle<v8::Function> callback = v8::Handle<v8::Function>::Cast(callback_val);
const int argc = 1;
v8::Handle<v8::Value> argv[argc] = { v8::Int32::New(char(p->vkCode)) };
printf("Calling onKeyDown\n");
v8::Handle<v8::Value> result = callback->Call(g->_context->Global(), argc, argv);
Some of this may actually not work in the end, but it just never gets called, when I run the program, and define: onKeyDown = function(key) {...}; I can see that onKeyDown is working just fine, I can use all of my bound c++ method etc from JS, so this thing is just driving me batty.
Any help, maybe pointers to some educational materials would be much appreciated.
Just to be clear, this function in c: LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam) is never getting called, or never seeing a printf, and the output at the start says: Hook established, so windows is reporting the hook is established.
/Jason
A low-level hook, like WH_KEYBOARD_LL requires that your application pumps a message loop. That's the only way that Windows can break into your thread and make the call to the HookProc callback you registered.
A console mode app doesn't pump a message loop like regular Windows GUI apps do. Judging from your snippet, it isn't going to be easy to add one either. You'll need to create a thread.
Maybe this function will be of help to you?
GetAsyncKeyState