Related
I want to break from the windows message loop. Just like C++ how to break message loop in windows hook . I came up with one solution, which works fine for Window Desktop Application, but fails for Console Application. How can this happen?
EDIT: I upload my codes to https://github.com/hellohawaii3/Experiment , clone it and then you can reproduce my problem quickly. Thanks!
1.Why I want to do so?
I am writing a console application. First, users are asked to set some options which determine app's behaviors. Then, the app start the message loop and monitor the input of the keyboard/mouse. Users may want to change the setting, so I want to enable users to press some hotkey, quit from the message loop and go back to the beginning of the application.
If you know any way to implement this function without worrying about breaking from the message loop, please tell me! However, I also want to know why my solution fails for console app and works well for desktop app. Thanks for your help!
2.What have I tried.
I use a bool variable 'recieve_quit'. When certain key is pressed on the keyboard, the variable is setting to True by the hook callback function. For every loop getting message, check the variable 'recieve_quit' first and quit when the variable is False.
3.Result of my experiment
For Console APP, The variable 'recieve_quit' is set correctly when certain key is pressed, however, the message loop continues.
For Windows Desktop APP with GUI, I can quit from the message loop as expected.
4.Experiment settings
I am using VS2019, C++, windows 10 home 1909.
I use dll inject to set hook for my console app.
5.My code
I provide toy example codes here, most of which is generated by Visual Studio automatically, do not bother if you think my codes are too loog.
(a)My console app
Console:
// Console.cpp
#include <iostream>
#include "dll_func.h"
#include <windows.h>
int main()
{
MSG msg;
HHOOK hhook_tmp2 = SetWindowsHookEx(WH_KEYBOARD_LL, HandleKeyboardEvent, hDllModule, 0);
while (recieve_quit == false)
{
if (GetMessage(&msg, nullptr, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
MessageBox(NULL, TEXT("APP QUIT"), TEXT(" "), MB_OK);
}
(b)my dll containing hook function
My dll_func.h file, following the doc https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-160
#pragma once
#ifdef DLL1_EXPORTS
#define DLLFUNC_API __declspec(dllexport)
#else
#define DLLFUNC_API __declspec(dllimport)
#endif
#include "framework.h"
extern "C" DLLFUNC_API bool recieve_quit;
extern "C" DLLFUNC_API LRESULT CALLBACK HandleKeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam);// refer to https://stackoverflow.com/a/60913531/9758790
extern "C" DLLFUNC_API HMODULE hDllModule;//or whatever name you like
My dll_func.cpp file, containing the definition of hook function.
#include "pch.h"
#include <windows.h>
#include "dll_func.h"
bool recieve_quit = false;
LRESULT CALLBACK HandleKeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
if (wParam == WM_KEYDOWN) {
if (p->vkCode == VK_F8) {
recieve_quit = true;
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
The dllmain.cpp is also modified a little after it is created by Visual Studio as suggested by https://stackoverflow.com/a/60913531/9758790 to get the hinstance of the dll for dll injection.
// dllmain.cpp
#include "pch.h"
#include "dll_func.h"
// refer to https://stackoverflow.com/a/60913531/9758790
HMODULE hDllModule;//or whatever name you like
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
hDllModule = hModule;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
(c) My Desktop application.
I select 'Creating Windows Desktop Application' when created the solution with Visual Studio. Most of the codes is generated automatically by VS. The codes I added and modifed is surrounded by ***** in the codes.
// GUI.cpp
//
#include "framework.h"
#include "GUI.h"
#define MAX_LOADSTRING 100
HINSTANCE hInst;
WCHAR szTitle[MAX_LOADSTRING];
WCHAR szWindowClass[MAX_LOADSTRING];
// *********************** ADDED BY ME! ***********************
// same as dll_func.cpp
bool recieve_quit = false;
LRESULT CALLBACK HandleKeyboardEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
//FILE* file;
//fopen_s(&file, "./temp0210222.txt", "a+");
//fprintf(file, "Function keyboard_hook called.n");
//fclose(file);
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
if (wParam == WM_KEYDOWN) {
if (p->vkCode == VK_F8) {
recieve_quit = true;
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
// *********************** END OF MY CODES ***********************
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// *********************** ADDED BY ME! ***********************
HHOOK hhook_tmp2 = SetWindowsHookEx(WH_KEYBOARD_LL, HandleKeyboardEvent, hInst, 0);
// *********************** END OF MY CODES ***********************
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_GUI, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GUI));
MSG msg;
// main message loop:
// *********************** MODIFIED BY ME! ***********************
//while (GetMessage(&msg, nullptr, 0, 0))
//{
// if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
// {
// TranslateMessage(&msg);
// DispatchMessage(&msg);
// }
//}
while (recieve_quit == false)
{
if (GetMessage(&msg, nullptr, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
MessageBox(NULL, TEXT("APP QUIT"), TEXT(" "), MB_OK);
// *********************** END OF MODIFICATION ***********************
return (int) msg.wParam;
}
//
// Function: MyRegisterClass()
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_GUI));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_GUI);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// Function: InitInstance(HINSTANCE, int)
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance;
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// Function: WndProc(HWND, UINT, WPARAM, LPARAM)
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// "About"
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
(d)Tips for reproducing my results
For Console APP: Build a new console application solution named Console, and copy my codes to replace Console.cpp. Add a new project to this solution, select Create new project -> DLL, name it as Dll1. Create dll_func.h, dll_func.c, and copy my codes in. Do not forget to modify dllmain.cpp, too. Set the path of AdditionalIncludeDirectories, add dll1.lib to AdditionalDependencies. Set the path to dll and lib files too.
For Windows Desktop APP: Build a now Windows Desktop App solution, name it as GUI. Copy my codes in GUI.cpp and simply run it. Press key F8, the app will quit and pop up a message box as expected.
This post explains why console apps dont receive keyboard messages and how they can handle them:
does not go inside the Windows GetMessage loop on console application
In your console case execution enters GetMessage and never exits it. The hook receives a notification and correctly sets recieve_quit. Since the execution never exits GetMessage, recieve_quit is not checked.
This answer is about handling getting keypresses in a console app:
https://stackoverflow.com/a/6479673/4240951
In general - add a hidden window to your console app or check GetAsyncState of the needed key.
There is no need to set hooks when you have a message loop. You may check keypresses as follows:
while (recieve_quit == false)
{
if (GetMessage(&msg, nullptr, 0, 0)) {
if (msg.message == WM_KEYDOWN && msg.wParam == VK_F8)
recieve_quit = true;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
I'm having trouble utilizing Win API's DwmDefWindowProc. It always returning false, even when DWM is enabled.
I'm sending a WM_NCHITTEST message to the window procedure to detect the action of the mouse position but it's not giving me accurate results (due to DWM being enabled and me needing to call DwmDefWindowProc beforehand).
I'm using a Windows 10 (Ver. 2004) machine and I have tested the same behavior on my Windows 7 virtual machine. If I change the combability of the executable to launch as Windows XP (Disabling DWM, I'm getting the expected behavior).
Otherwise, the information I'm getting back from WM_NCHITTEST is incorrect as the right side of the maximize button returns the expected HTMAXBUTTON while the left side of it returns HTREDUCE.
Reproducing the issue with the Windows Desktop Application template (found below). If you have DWM enabled (Most Windows 10 users would), the maximize button no longer works properly. If run the program in Visual Studio and select the Output tab, you'll see that when you hover to the left (green border in the picture below) of the maximize button you will get a HTMINBUTTON message while if you hover to the right (red border in the picture below) you will get the expected HTMAXBUTTON message.
Here's the sample code
// SimpleWindow.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "SimpleWindow.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
/* New Stuff */
#include <dwmapi.h>
#pragma comment(lib, "Dwmapi.lib")
void DWMExample(HWND hWnd, unsigned int msg, unsigned int wParam, int lParam);
LRESULT ProcessNCHitTest(HWND hWnd, int lParam);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_SIMPLEWINDOW, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow)) {
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SIMPLEWINDOW));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0)) {
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SIMPLEWINDOW));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_SIMPLEWINDOW);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd) {
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) {
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId) {
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
/* New Stuff */
if (message == WM_NCHITTEST) {
return ProcessNCHitTest(hWnd, lParam);
}
DWMExample(hWnd, message, wParam, lParam);
return DefWindowProc(hWnd, message, wParam, lParam);
}
void DWMExample(const HWND hWnd, const unsigned int msg, const unsigned int wParam, const int lParam)
{
switch (msg) {
case WM_NCMOUSEMOVE:
case WM_MOUSEMOVE:
{
const auto ht = SendMessageA(hWnd, WM_NCHITTEST, wParam, lParam);
switch (ht) {
case HTBORDER:
OutputDebugStringA("HTBORDER\n");
break;
case HTBOTTOM:
OutputDebugStringA("HTBOTTOM\n");
break;
case HTBOTTOMLEFT:
OutputDebugStringA("HTBOTTOMLEFT\n");
break;
case HTBOTTOMRIGHT:
OutputDebugStringA("HTBOTTOMRIGHT\n");
break;
case HTCAPTION:
OutputDebugStringA("HTCAPTION\n");
break;
case HTCLIENT:
OutputDebugStringA("HTCLIENT\n");
break;
case HTCLOSE:
OutputDebugStringA("HTCLOSE\n");
break;
case HTERROR:
OutputDebugStringA("HTERROR\n");
break;
case HTGROWBOX:
OutputDebugStringA("HTGROWBOX\n");
break;
case HTHELP:
OutputDebugStringA("HTHELP\n");
break;
case HTHSCROLL:
OutputDebugStringA("HTHSCROLL\n");
break;
case HTLEFT:
OutputDebugStringA("HTLEFT\n");
break;
case HTMENU:
OutputDebugStringA("HTMENU\n");
break;
case HTMAXBUTTON:
OutputDebugStringA("HTMAXBUTTON\n");
break;
case HTMINBUTTON:
OutputDebugStringA("HTMINBUTTON\n");
break;
case HTNOWHERE:
OutputDebugStringA("HTNOWHERE\n");
break;
// case HTREDUCE:
// OutputDebugStringA("HTREDUCE\n");
// break;
case HTRIGHT:
OutputDebugStringA("HTRIGHT\n");
break;
// case HTSIZE:
// OutputDebugStringA("HTSIZE\n");
// break;
case HTSYSMENU:
OutputDebugStringA("HTSYSMENU\n");
break;
case HTTOP:
OutputDebugStringA("HTTOP\n");
break;
case HTTOPLEFT:
OutputDebugStringA("HTTOPLEFT\n");
break;
case HTTOPRIGHT:
OutputDebugStringA("HTTOPRIGHT\n");
break;
case HTTRANSPARENT:
OutputDebugStringA("HTTRANSPARENT\n");
break;
case HTVSCROLL:
OutputDebugStringA("HTVSCROLL\n");
break;
// case HTZOOM:
// OutputDebugStringA("HTZOOM\n");
// break;
}
}
break;
}
}
LRESULT ProcessNCHitTest(const HWND hWnd, const int lParam)
{
BOOL isDWMEnabled = false;
if (FAILED(DwmIsCompositionEnabled(&isDWMEnabled))) {
return DefWindowProcA(hWnd, WM_NCHITTEST, 0, lParam);
}
if (!isDWMEnabled) {
return DefWindowProcA(hWnd, WM_NCHITTEST, 0, lParam);
}
LRESULT result = 0;
if (!DwmDefWindowProc(hWnd, WM_NCHITTEST, 0, lParam, &result)) {
return DefWindowProcA(hWnd, WM_NCHITTEST, 0, lParam);
}
return result;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message) {
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
Any idea where I'm going wrong? Any help would be appreciated!
I used the MSVC++ wizard to create a win32 application. I added a new menu resource and added the typical 'File'->'Exit' etc.. Then I added it to the main dialog under the properties in msvc++. When I run the form it shows the menu on the form but if I click on File it doesn't even do the hover and it doesn't show the popup of Exit. Its almost like it's disabled. I really didn't think I needed to add any code. Any help is appreciated. Thanks.
#include "stdafx.h"
#define MAX_LOADSTRING 100
struct _globals {
HINSTANCE hInst;
HWND hWnd;
} g;
LRESULT CALLBACK DialogProc(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
InitCommonControls();
g.hInst = hInstance;
g.hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN), NULL, (DLGPROC)DialogProc);
if (g.hWnd == NULL) {
GetLastError();
return FALSE;
}
ShowWindow(g.hWnd, nCmdShow);
UpdateWindow(g.hWnd);
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_ACCELLS));
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
if (TranslateAccelerator(g.hWnd, hAccelTable, &msg))
continue;
if (IsDialogMessage(g.hWnd, &msg))
continue;
// process message
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK DialogProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
break;
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
switch (wmId)
{
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
Your DialogProc function looks more like a window procedure than a dialog procedure. Unlike window procedures, dalog procedures do not return LRESULT values, they return BOOL values, and they do not call DefWindowProc. There are some other differences as well.
I'm trying to handle mouse events on my screen(outside of client window). I use pure Win32 API.
I have created separate DLL with SetWindowHookEx function and reference this to my Win32 Application. But its handle only window event, and when mouse is outside of window or window is not active nothing happens.
//Hook.h
#ifndef _DEFINED_44E531B1_14D3_11d5_A025_006067718D04
#define _DEFINED_44E531B1_14D3_11d5_A025_006067718D04
#if _MSC_VER > 1000
#pragma once
#endif
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#ifdef _COMPILING_44E531B1_14D3_11d5_A025_006067718D04
#define LIBSPEC __declspec(dllexport)
#else
#define LIBSPEC __declspec(dllimport)
#endif // _COMPILING_44E531B1_14D3_11d5_A025_006067718D04
LIBSPEC BOOL InstallHook(HWND hWnd);
LIBSPEC BOOL UnInstallHook(HWND hWnd);
#undef LIBSPEC
#ifdef __cplusplus
}
#define UWM_MOUSEMOVE_MSG (L"UWM_MOUSEMOVE_USER_MSG")
#define UWM_MOUSELBUTTONUP_MSG ( L"UWM_MOUSELBUTTONUP_USER_MSG" )
#define UWM_MOUSELBUTTONDOWN_MSG ( L"UWM_MOUSELBUTTONDOWN_USER_MSG" )
#define UWM_MOUSERBUTTONUP_MSG ( L"UWM_MOUSERBUTTONUP_USER_MSG" )
#define UWM_MOUSERBUTTONDOWN_MSG ( L"UWM_MOUSERBUTTONDOWN_USER_MSG" )
#define UWM_MOUSELDBCLICK_MSG ( L"UWM_MOUSERBUTTONDOWN_USER_MSG" )
#endif // __cplusplus
#endif // _DEFINED_44E531B1_14D3_11d5_A025_006067718D04
//Hook.cpp
// Hook.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "Hook.h"
#pragma data_seg()
#pragma comment(linker, "/section:.Segment,rws")
HWND hWndServer = NULL;
UINT UWM_MOUSEMOVE;
UINT UWM_MOUSELBUTTONUP;
UINT UWM_MOUSELBUTTONDOWN;
UINT UWM_MOUSERBUTTONUP;
UINT UWM_MOUSERBUTTONDOWN;
UINT UWM_MOUSELDBCLICK;
HINSTANCE hInst;
//HWND hWndServer = NULL;
HHOOK hook;
static LRESULT CALLBACK MouseMsgProc(UINT nCode, WPARAM wParam, LPARAM lParam)
{
if(nCode < 0)
{
CallNextHookEx(hook, nCode, wParam, lParam);
return 0;
}
LPMSG msg = (LPMSG)lParam;
switch( msg->message )
{
case WM_LBUTTONDBLCLK:
SendMessage( hWndServer, UWM_MOUSELDBCLICK, 0 , 0);
break;
case WM_MOUSEMOVE:
SendMessage( hWndServer, UWM_MOUSEMOVE, 0, 0);
break;
case WM_NCMOUSEMOVE:
SendMessage( hWndServer, UWM_MOUSEMOVE, 0, 0);
break;
case WM_LBUTTONDOWN:
SendMessage( hWndServer, UWM_MOUSELBUTTONDOWN, 0 , 0 );
break;
case WM_NCLBUTTONDOWN:
SendMessage( hWndServer, UWM_MOUSELBUTTONDOWN, 0 , 0);
break;
case WM_LBUTTONUP:
SendMessage( hWndServer, UWM_MOUSELBUTTONUP, 0 , 0 );
break;
case WM_NCLBUTTONUP:
SendMessage( hWndServer, UWM_MOUSELBUTTONUP, 0 , 0);
break;
case WM_RBUTTONDOWN:
SendMessage( hWndServer, UWM_MOUSERBUTTONDOWN, 0 , 0 );
break;
case WM_NCRBUTTONDOWN:
SendMessage( hWndServer, UWM_MOUSERBUTTONDOWN, 0 , 0);
break;
case WM_RBUTTONUP:
SendMessage( hWndServer, UWM_MOUSERBUTTONUP, 0 , 0 );
break;
case WM_NCRBUTTONUP:
SendMessage( hWndServer, UWM_MOUSERBUTTONUP, 0 , 0);
break;
default:
break;
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
__declspec(dllexport) BOOL InstallHook( HWND hWndParent)
{
if(hWndServer != NULL)
return FALSE; // already hooked!
hook = SetWindowsHookEx( WH_GETMESSAGE, (HOOKPROC)MouseMsgProc,
hInst, 0);
if(hook != NULL)
{
hWndServer = hWndParent;
return TRUE;
}
return FALSE;
}
__declspec(dllexport) BOOL UnInstallHook( HWND hWndParent )
{
if(hWndParent != hWndServer || hWndParent == NULL)
return FALSE;
BOOL unhooked = UnhookWindowsHookEx(hook);
if(unhooked)
hWndServer = NULL;
return unhooked;
return TRUE;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
hInst = hModule;
UWM_MOUSEMOVE = ::RegisterWindowMessage(UWM_MOUSEMOVE_MSG);
UWM_MOUSELBUTTONUP = ::RegisterWindowMessage(UWM_MOUSELBUTTONUP_MSG);
UWM_MOUSELBUTTONDOWN = ::RegisterWindowMessage(UWM_MOUSELBUTTONDOWN_MSG);
UWM_MOUSERBUTTONUP = ::RegisterWindowMessage(UWM_MOUSERBUTTONUP_MSG);
UWM_MOUSERBUTTONDOWN = ::RegisterWindowMessage(UWM_MOUSERBUTTONDOWN_MSG);
UWM_MOUSELDBCLICK = ::RegisterWindowMessage(UWM_MOUSELDBCLICK_MSG);
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//Win32 Application main.cpp
#include "stdafx.h"
#include "stdafx.h"
#include <sstream>
#include "strsafe.h"
#include "../Hook/Hook.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
//Mouse Events
static UINT UWM_MOUSEDBCLICK = ::RegisterWindowMessage( UWM_MOUSELDBCLICK_MSG );
static UINT UWM_MOUSELBUTTONUP = ::RegisterWindowMessage(UWM_MOUSELBUTTONUP_MSG);;
static UINT UWM_MOUSELBUTTONDOWN = ::RegisterWindowMessage(UWM_MOUSELBUTTONDOWN_MSG);
static UINT UWM_MOUSERBUTTONUP = ::RegisterWindowMessage(UWM_MOUSERBUTTONUP_MSG);
static UINT UWM_MOUSERBUTTONDOWN = ::RegisterWindowMessage(UWM_MOUSERBUTTONDOWN_MSG);
static UINT UWM_MOUSEMOVE = ::RegisterWindowMessage(UWM_MOUSEMOVE_MSG);
//
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_ACTIONX, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_ACTIONX));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ACTIONX));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_ACTIONX);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
BOOL result=InstallHook(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
//Global Mouse Move Handle
if(message==UWM_MOUSEMOVE){
MessageBox(
NULL,
(LPCWSTR)L"Resource not available\nDo you want to try again?",
(LPCWSTR)L"Account Details",
MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2
);
return 0;
}
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
case IDM_PLAY:
PlayMouse();
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
Use WH_MOUSE hook to hook mouse messages only.
Few suggestions:
Ensure you hook installed successfully (SetWindowsHookEx returned non-NULL value)
Ensure messages delivered to hook procedure (Set breakpoint to these points or use trace functions)
You either need to send HWND of target window to the each process or send broadcast message
For Windows Vista and later processes with lower privileges cannot send messages to process with higher privileges. You need to use ChangeWindowMessageFilter to add necessary messages to the filter
Use PostMesssage instead of SendMessage, you don't need blocking calls here anyway
while defining a hook you have to provide the handle for the window for which you want to intercept the signal. Maybe passing handle of the desktop there can catch all the mouse event even outside the client window.
If I create a child window (In this case window "About") to the main window, the dialog box for some reason is not called. If you do not the child window is a dialog box called normal and works fine. GetLastError returns the error number 1812 (The specified image file did not contain a resource section.). But from a resource file everything is fine. And as I said, if you do not create a child window then everything works fine. What's the problem?
#include <windows.h>
#include "resource.h"
LONG WINAPI WndProc(HWND, UINT, WPARAM,LPARAM);
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK PointsProc(HWND hPoints, UINT message, WPARAM wParam,LPARAM lParam);
HINSTANCE hInst;
HWND hPoints;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
hInst = hInstance;
HWND hwnd;
MSG msg;
WNDCLASS w;
memset(&w,0,sizeof(WNDCLASS));
w.style = CS_HREDRAW | CS_VREDRAW;
w.lpfnWndProc = WndProc;
w.hInstance = hInstance;
w.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
w.lpszClassName = L"My Class";
RegisterClass(&w);
hwnd = CreateWindow(L"My Class", L"My title", WS_OVERLAPPEDWINDOW,
300, 200, 200, 180, NULL, NULL, hInstance, NULL);
HMENU main_menu = CreateMenu();
AppendMenu(main_menu, MF_STRING, 1111, L"Box");
WNDCLASS w2;
memset(&w2, 0, sizeof(WNDCLASS));
w2.lpfnWndProc = (WNDPROC)PointsProc;
w2.hInstance = hInst;
w2.lpszClassName = L"About";
w2.hCursor = LoadCursor(NULL, IDC_ARROW);
w2.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(111, 111, 111));
RegisterClass(&w2);
hPoints = CreateWindowEx(0, L"About", (LPCTSTR) NULL,
WS_CHILD | WS_BORDER | WS_VISIBLE | WS_DISABLED, 10, 10,
100, 100, hwnd, (HMENU)1112, hInst, NULL);
ShowWindow(hPoints,SW_NORMAL);
UpdateWindow(hPoints);
SetMenu(hwnd, main_menu);
ShowWindow(hwnd,nCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LONG WINAPI WndProc(HWND hwnd, UINT Message, WPARAM wparam, LPARAM lparam)
{
switch (Message)
{
case WM_COMMAND:
switch(LOWORD(wparam))
{
case 1111:
DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), hwnd, About);
return 0;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, Message, wparam, lparam);
}
return 0;
}
LRESULT CALLBACK PointsProc(HWND hPoints, UINT message, WPARAM wParam,LPARAM lParam)
{
switch(message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_PAINT:
break;
default:
return DefWindowProc(hPoints, message, wParam, lParam);
}
return 0;
}
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
The dialog box is called, only it takes a long time because PointsProc() is looping...
The problem was the break; while handling WM_PAINT in PointsProc() -- it then skips calling DefWindowProc(), so the window keeps getting WM_PAINT messages because the window remains invalid.
// case WM_PAINT:
// break;