Write a C program that closes any window just by placing the cursor on the ‘Close’ button in the title bar of it.
Here is a sample C program that installs a global mouse hook and closes a window when the cursor is placed over the ‘Close’ button in the title bar:
#include <windows.h>
#include <stdio.h>
// callback function for the mouse hook
LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HC_ACTION)
{
// get the mouse event and the window handle
PMOUSEHOOKSTRUCT p = (PMOUSEHOOKSTRUCT) lParam;
HWND hwnd = p->hwnd;
// get the window rect and the mouse position
RECT rect;
GetWindowRect(hwnd, &rect);
POINT pt = p->pt;
// check if the mouse is over the 'Close' button
if (pt.x >= rect.right - 35 && pt.x < rect.right - 15 &&
pt.y >= rect.top + 5 && pt.y < rect.top + 25)
{
// close the window
PostMessage(hwnd, WM_CLOSE, 0, 0);
}
}
// pass the event to the next hook in the chain
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int main()
{
// install the mouse hook
HHOOK hHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0);
if (hHook == NULL)
{
printf("Error installing mouse hook: %d\n", GetLastError());
return 1;
}
// run the message loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// uninstall the mouse hook
UnhookWindowsHookEx(hHook);
return 0;
}
This program installs a global mouse hook using the SetWindowsHookEx
function and defines a callback function MouseHookProc
that is called whenever a mouse event occurs. The callback function gets the window handle and the mouse position, calculates the position of the ‘Close’ button in the title bar, and closes the window if the mouse is over the button.
The program also runs a message loop using GetMessage
, TranslateMessage
, and DispatchMessage
to process mouse events. When the program is closed, the mouse hook is uninstalled using the UnhookWindowsHookEx
function.
Note that this program will only work on Windows systems. If we want to close windows using the mouse on a different operating system, we will need to use a different approach.
Leave a Comment